将JSON字符串转换为JSON数组

时间:2018-05-31 18:46:01

标签: javascript arrays json

我有这个字符串:

s = '{"segmentTime3":Tue, 29 May 2018 10:10:00 UTC +00:00, "topic":"topic11", "personRows3":[{"personI3":"Georgia", "personR3":"GS - guest"}]}, {"segmentTime3":Tue, 29 May 2018 10:15:00 UTC +00:00, "topic":"topic2", "personRows3":[{"personI3":"newPers", "personR3":"CS - correspondant"}, {"personI3":"Arkansas", "personR3":"CS - correspondant"}]}'   

我想转换为JSON数组:

a = [
      {"segmentTime3":Tue, 29 May 2018 10:10:00 UTC +00:00, "topic":"topic11", "personRows3":[{"personI3":"Georgia", "personR3":"GS - guest"}]},    
      {"segmentTime3":Tue, 29 May 2018 10:15:00 UTC +00:00, "topic":"topic2", "personRows3":[{"personI3":"newPers", "personR3":"CS - correspondant"}, {"personI3":"Arkansas", "personR3":"CS - correspondant"}]}
    ]   

我试过但得到一个1元素的数组而不是2:

a = JSON.parse('[' + s + ']');  // create array
a = [s];
a = [JSON.stringify(s)];   

2 个答案:

答案 0 :(得分:0)

观察:

您的JSON String无效JSON

  • 它应该是一个对象数组而不是多个单独的对象。
  • 时间(2018年5月29日星期二,10:10:00 UTC + 00:00)应附在""

<强>样本

&#13;
&#13;
var s = '[{"segmentTime3":"Tue, 29 May 2018 10:10:00 UTC +00:00", "topic":"topic11", "personRows3":[{"personI3":"Georgia", "personR3":"GS - guest"}]}, {"segmentTime3":"Tue, 29 May 2018 10:15:00 UTC +00:00", "topic":"topic2", "personRows3":[{"personI3":"newPers", "personR3":"CS - correspondant"}, {"personI3":"Arkansas", "personR3":"CS - correspondant"}]}]';

var jsonObj = JSON.parse(s);

console.log(jsonObj);
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

你可以试试吗?     s ='{“elements”:['+ s +']}';

将它解析为一个对象,如果你访问该对象的“elements”键,你应该得到数组