将字符串格式的数组转换为javascript数组

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

我有一个字符串格式的数组,

var str = { id: 123,
            changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
          }
var d = str.changes

我试图通过组合split(),replace(),slice()等...甚至JSON.parse(),使用不同的方法从字符串格式转换'changes'数组,但是没有任何效果。

有没有办法将其转换为javascript数组?

javascript arrays string
2个回答
0
投票

如果响应始终是您提供的格式,那么您可以创建有效的JSON

var str = { id: 123,
            changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
          }
let changes = str.changes.replace(/\[\[/g,"[{").replace(/\], \[/g,"},{").replace(/\]\]/g,"}]")
console.log(changes)
changes = changes.replace(/(\w+):/g,'"$1":').replace(/:([\w ]+)([},])/g,':"$1"$2')
console.log(JSON.parse(changes))

0
投票

我认为问题在于关键的“更改”没有任何有效的JSON。您可以验证其格式here

[如果'changes'键中存在有效的JSON,类似:

    var str = { id: 123,
            changes: `[
  [
    {
      "atr": "test1",
      "old": null,
      "new": null
    }
  ],
  [
    {
      "atr": "messageText",
      "old": "test here",
      "new": "hello test"
    }
  ],
  [
    {
      "atr": "status",
      "old": null,
      "new": 1
    }
  ]
]`
          }
var d = JSON.parse(str.changes);

    console.log(d);

//str.changes Object:
[[[object Object] {
  atr: "test1",
  new: null,
  old: null
}], [[object Object] {
  atr: "messageText",
  new: "hello test",
  old: "test here"
}], [[object Object] {
  atr: "status",
  new: 1,
  old: null
}]]
© www.soinside.com 2019 - 2024. All rights reserved.