Anna Pawlicka
Anna Pawlicka

Reputation: 757

Parse array-like string into an array of json objects in JavaScript

I have a String in the following format:

[{"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"}]}]

It resembles an array of two json objects. I need to retrieve these JSON objects.

I have tried to parse it using JSON.parse(str) but complaints about the "," that separates JSONs in this array-like structure.

I have tried doing str.split(",") but it splits by each comma, e.g.

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

  [1] "unit":"%"

I have tried removing first and last brackets and reading it as an array:

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

but it creates an array of a single string.

Any help on how to read that string into an array of JSON objects will be greatly appreciated.

Upvotes: 0

Views: 174

Answers (2)

Cracker0dks
Cracker0dks

Reputation: 2490

this works for me (no JSON parse error) > 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"}]}]');

tried it in chrome console

Upvotes: 1

Swifty
Swifty

Reputation: 1432

try this:

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

Upvotes: 0

Related Questions