在JavaScript中将类似数组的字符串解析为json对象数组

时间:2013-11-25 14:04:00

标签: javascript arrays json

我有一个以下格式的字符串:

[{"type":"relativeHumidity","unit":"%","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]},{"type":"temperature","unit":"C","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]}]

它类似于两个json对象的数组。我需要检索这些JSON对象。

我曾尝试使用JSON.parse(str)解析它,但抱怨“,”将JSON分成这种类似数组的结构。

我尝试过str.split(“,”),但它按每个逗号分隔,例如。

  [0] [{"type":"relativeHumidity"

  [1] "unit":"%"

我尝试删除第一个和最后一个括号并将其作为数组读取:

var arr = [str.substr(1, value.length - 2)];

[ '{"type":"relativeHumidity","unit":"%","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]},{"type":"temperature","unit":"C","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]}' ]

但它会创建一个单个字符串的数组。

有关如何将该字符串读入JSON对象数组的任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:1)

这适用于我(没有JSON解析错误)> JSON.parse('[{"type":"relativeHumidity","unit":"%","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]},{"type":"temperature","unit":"C","resolution":300,"accuracy":0.0,"period":"INSTANT","correction":false,"completenessRatios":[{"completenessRatio":0.0,"period":"SIX_MONTHS"},{"completenessRatio":0.0,"period":"THIRTY_DAYS"},{"completenessRatio":0.5789037386601943,"period":"FULL_HISTORY"}]}]');

在Chrome控制台中尝试了

答案 1 :(得分:0)

试试这个:

var jsonArray = JSON.stringify({ "type":"relativeHumidity","unit":"%","resolution":300,"accuracy":0.0;})