[英]Get square brackets instead of curly in json in javascript
If I want to update object in elasticsearch script, thus I need to send some weird modification of JSON ( https://discuss.elastic.co/t/updating-an-object-field/110735/2 ).如果我想在 elasticsearch 脚本中更新对象,因此我需要发送一些奇怪的 JSON 修改( https://discuss.elastic.co/t/updating-an-object-field/110735/2 )。 I don't really know what language is that or why would they do that.
我真的不知道那是什么语言,也不知道他们为什么要这样做。
For example, if input is例如,如果输入是
{"id": 2, "name": "John"}
I need the way in javascript to make it我需要 javascript 中的方法来实现它
["id": 2, "name": "John"]
First sloultion would be第一个 slollion 将是
standardJson.replace('{', '[').replace('}', ']')
However, I am worried about curly brackets inside values, so above solution would override但是,我担心值内的大括号,因此上述解决方案将覆盖
"name": "{John"
to到
"name": "[Jonh"
And I don't want that.我不想要那样。 In fact, I need to this inside general purporse library, so I can't just hope this case will not happen.
事实上,我需要在通用库中使用这个,所以我不能只是希望这种情况不会发生。
Try this it will only change outer curly braces to brackets.试试这个它只会将外部花括号更改为括号。
let a =`{"id": 2, "name": "{John}" }` console.log(a.replace(/^\\{(.*)\\}$/,"[$1]"));
Explicit approach based on input object parsing with Object.entries and Array.prototype.map :基于使用Object.entries和Array.prototype.map解析输入对象的显式方法:
const inputData = { "id": 2, "name": "{John}" }; const parsed = `[` + Object.entries(inputData) .map(v => `"${v[0]}": ` + (typeof v[1] === `string` ? `"${v[1]}"` : v[1]) ) .join(`, `) + `]`; console.log(parsed); // ["id": 2, "name": "{John}"]
To handle nested objects, the procedure can be run recursively with additional parsing branch:要处理嵌套对象,可以使用附加解析分支递归运行该过程:
const inputData = { "id": 2, "name": "{John}", "foo": { "bar": "{zoo}" } }; const parse = (data) => `[` + Object.entries(data) .map(v => `"${v[0]}": ` + ( typeof v[1] === `string` ? `"${v[1]}"` : ( typeof v[1] === "object" ? parse(v[1]) : v[1] ) ) ) .join(`, `) + `]`; console.log(parse(inputData)); // ["id": 2, "name": "{John}", "foo": ["bar": "{zoo}"]]
Nested arrays also can be processed in the same way, just need to add 1 more condition branch.嵌套数组也可以用同样的方式处理,只需要再增加 1 个条件分支。
Based on answers posted here, arrived at final solution, that is a more readable and handles some cases not handled in previous answers (booleans, nulls, numbers, undefined, nested arrays etc)基于此处发布的答案,得出了最终解决方案,该解决方案更具可读性,并处理了以前答案中未处理的一些情况(布尔值、空值、数字、未定义、嵌套数组等)
function toElasticStupidJson(data) {
if(isPrimitive(data)) return primitiveDisplay(data)
else if(typeof data === 'object') return objectDisplay(data)
}
function objectDisplay(data) {
let inner = ''
if(Array.isArray(data)) inner = data.filter(d => d !== undefined).map(toElasticStupidJson).join(', ')
else inner = Object.entries(data)
.filter(keyValue => keyValue[1] !== undefined)
.map(keyValue => {
return `"${keyValue[0]}": ` + toElasticStupidJson(keyValue[1])
})
.join(', ')
return `[${inner}]`
}
function isPrimitive(value) {
return typeof value === 'string'
|| typeof value === 'number'
|| typeof value === 'boolean'
|| value === null
}
function primitiveDisplay(value) {
if(typeof value === 'string') return `"${value}"`
if(typeof value === 'number') return `${value}`
if(typeof value === 'boolean') return `${value}`
if(value === null) return 'null'
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.