繁体   English   中英

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

[英]Get square brackets instead of curly in json in javascript

如果我想在 elasticsearch 脚本中更新对象,因此我需要发送一些奇怪的 JSON 修改( https://discuss.elastic.co/t/updating-an-object-field/110735/2 )。 我真的不知道那是什么语言,也不知道他们为什么要这样做。

例如,如果输入是

{"id": 2, "name": "John"}

我需要 javascript 中的方法来实现它

["id": 2, "name": "John"]

第一个 slollion 将是

standardJson.replace('{', '[').replace('}', ']')

但是,我担心值内的大括号,因此上述解决方案将覆盖

"name": "{John"

"name": "[Jonh"

我不想要那样。 事实上,我需要在通用库中使用这个,所以我不能只是希望这种情况不会发生。

试试这个它只会将外部花括号更改为括号。

 let a =`{"id": 2, "name": "{John}" }` console.log(a.replace(/^\\{(.*)\\}$/,"[$1]"));

基于使用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}"]

要处理嵌套对象,可以使用附加解析分支递归运行该过程:

 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}"]]

嵌套数组也可以用同样的方式处理,只需要再增加 1 个条件分支。

基于此处发布的答案,得出了最终解决方案,该解决方案更具可读性,并处理了以前答案中未处理的一些情况(布尔值、空值、数字、未定义、嵌套数组等)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM