将相同格式的字符串转换为对象

时间:2017-08-16 09:26:56

标签: javascript arrays json string object

如果我有如下字符串:

[{"id":123, "name": "Sally", "age": 36}
{"id":138, "name": "Nicholas", "age": 48}
{"id":194, "name": "Steven", "age": 25}]

我有办法将它转换为对象吗?因为,他们的格式几乎相同。如果我错了,请纠正我并告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

您没有有效的json,如果您自己创建

,可以添加,
[{"id":123, "name": "Sally", "age": 36} // no , not valid
{"id":138, "name": "Nicholas", "age": 48} // no , not valid
{"id":194, "name": "Steven", "age": 25}]

[{"id":123, "name": "Sally", "age": 36}, // <- you need , here
{"id":138, "name": "Nicholas", "age": 48}, // <- you need , here
{"id":194, "name": "Steven", "age": 25}]

但是如果从某个地方获取此字符串,您可以在执行,之前添加JSON.parse并使您的字符串成为有效的json。

&#13;
&#13;
var a = `[{"id":123, "name": "Sally", "age": 36}
{"id":138, "name": "Nicholas", "age": 48}
{"id":194, "name": "Steven", "age": 25}]`

var b = JSON.parse(a.replace(/\n/gim, ','));
console.log (b)
&#13;
&#13;
&#13;