简体   繁体   English

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

[英]Convert an array in string format to javascript array

I have an array which is in string format,我有一个字符串格式的数组,

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

I tried to convert the 'changes' array from string format using different methods by combining split() , replace() , slice() etc...and even JSON.parse() , but nothing worked.我尝试通过组合split()replace()slice()等...甚至JSON.parse()使用不同的方法将“更改”数组从字符串格式转换,但没有任何效果。

Is there any way to convert this into javascript array?有什么方法可以将其转换为 javascript 数组?

Note that the string is not valid anything but string.请注意,该字符串除了字符串之外的任何内容均无效。 It is not a valid array, and the string is not valid JSON.它不是一个有效的数组,并且字符串是无效的 JSON。

If you can, get the server to change it to the valid JSON string如果可以,请让服务器将其更改为有效的 JSON 字符串

"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"

If the response is ALWAYS on the format you gave, then you can create valid JSON如果响应始终是您提供的格式,那么您可以创建有效的 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]]" } // change the inner [ ] to { } let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]") // change the unquoted keys and values to quoted keys and values changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2') // parse the object changes = JSON.parse(changes); // replace "null" with null - could have been done above bt the regex would be nasty changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null"? null: item[key])) console.log(changes)

I think the problem is that the key 'changes' do not any valid JSON.我认为问题在于关键的“更改”没有任何有效的 JSON。 You can validate, format it here .您可以在此处验证、格式化。

If there is a valid JSON in 'changes' key, It can be converted to Js array using JSON.parse();, Something like:如果 'changes' 键中有一个有效的 JSON,它可以使用 JSON.parse(); 转换为 Js 数组,类似:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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