获取方括号而不是javascript中json中的大括号

问题描述 投票:-1回答:2

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

例如,如果输入为

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

我需要用javascript制作的方法

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

首先污蔑是

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

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

"name": "{John"

to

"name": "[Jonh"

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

javascript json replace
2个回答
0
投票

尝试此操作只会将外部花括号改为方括号。

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

0
投票

基于基于输入对象的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个条件分支。


0
投票
var newObject = {"id": 2, "name": "John"};
var square = '[' + Object.keys(newObject).map(
    function(key){
       return '"' + key + '": ' + newObject[key];
    }
    ).join(', ') + ']';
console.log(square);
© www.soinside.com 2019 - 2024. All rights reserved.