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 ). 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
["id": 2, "name": "John"]
First sloultion would be
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 :
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.
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'
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.