I am trying to parse data from Google Analytics for a reporting tool on a website and can bring back the data without a problem. I am then using that data to generate a FusionChart object:
The data I am using in the 'data' element is a label/value pair bination and if I explicity enter the following:
[{ "label":"1","value":"34" },"label":"2","value":"72" },...]
the graph works fine (shows labels etc).
However, the string I am using is being parsed as:
[{ "label":["1"],"value":["34"] },"label":["2"],"value":["72"] },...]
(Note the additional square brackets around the value elements of the keys)
Having these square brackets is causing no end of issues so anyone got an idea how to parse the data without these? I have trying string replace on the elmments but no luck!
Thanks
I am trying to parse data from Google Analytics for a reporting tool on a website and can bring back the data without a problem. I am then using that data to generate a FusionChart object:
The data I am using in the 'data' element is a label/value pair bination and if I explicity enter the following:
[{ "label":"1","value":"34" },"label":"2","value":"72" },...]
the graph works fine (shows labels etc).
However, the string I am using is being parsed as:
[{ "label":["1"],"value":["34"] },"label":["2"],"value":["72"] },...]
(Note the additional square brackets around the value elements of the keys)
Having these square brackets is causing no end of issues so anyone got an idea how to parse the data without these? I have trying string replace on the elmments but no luck!
Thanks
Share Improve this question edited Jan 15, 2019 at 16:40 Alfabravo 7,5896 gold badges49 silver badges83 bronze badges asked Jan 15, 2019 at 16:40 Fraser MathiesonFraser Mathieson 571 silver badge6 bronze badges 1- 2 I mean... once you parse it, it's simply an array of objects. You can manipulate it with ordinary array/object methods. – Kevin B Commented Jan 15, 2019 at 16:41
2 Answers
Reset to default 4If you know that each label and value will be a one-element array, you can use something an array method like map
to clean up the data.
let obj = [{ "label":["1"],"value":["34"] }, { "label":["2"],"value":["72"] }];
let cleaned = obj.map(item => {
return { label: item.label[0], value: item.value[0] };
});
console.log(cleaned);
If you are parsing the string from a different service than you can alter the JSON. You can write a custom parser reviver to change it to be strings instead of an array.
var json = '[{ "label":["1"],"value":["34"] },{"label":["2"],"value":["72"]}]'
var parsed = JSON.parse(json, (key, value) => ['label', 'value'].includes(key) ? value[0] : value)
console.log(parsed)
If it is ing from a different source and it is already an object than you can loop over the array of objects and convert it to a string.