简体   繁体   English

在javascript中获取方括号而不是在json中的卷曲

[英]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.entriesArray.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.

相关问题 JavaScript大括号和方括号的区别 - JavaScript difference between curly brackets and square brackets 将方括号和花括号替换为javascript或jquery中的圆括号 - replace square bracket & curly brackets to round brackets in javascript or jquery 从PHP创建JavaScript数组–方括号和花括号 - Creating a JavaScript array from PHP – square brackets and curly braces 用大括号替换所有方括号 - Replacing all square brackets with curly brackets JavaScript JSON object 名称中带有方括号和空格 - JavaScript JSON object with square brackets and spaces in name 如果在 javascript 中的大括号内有任何带方括号的占位符,如何将字符串更改为新字符串? - How can I change a string into new string if it has any placeholders with square brackets inside curly brackets in javascript? 使用javascript / Jquery在方括号内获取字符串 - Get string inside square brackets with javascript/Jquery 如何使用JavaScript在方括号内获取属性 - How to get attribute inside square brackets with JavaScript 如何用方括号替换打开和关闭花括号,并删除Java脚本ES6中json数组上的标签 - How to replace opening and closing curly braces by square brackets and remove labels on a json array in Java script ES6 从PHP数组到Javascript数组花括号与方括号 - going from PHP arrays to Javascript arrays curly braces vs square brackets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM