0

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 combination 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

1
  • 2
    I mean... once you parse it, it's simply an array of objects. You can manipulate it with ordinary array/object methods. Commented Jan 15, 2019 at 16:41

2 Answers 2

4

If 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);

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure, I thought it was a reasonable way to clean the data given the object's format. I'm hopeful whoever downvoted can leave me a note to help me understand why the answer is not sufficient.
Honestly, this is a clean way to achieve what OP asked you. You got an upvote from me.
Don't know why this has been downvoted - maybe by someone who doesn't agree with method. I will give this a go. Thanks ;)
1

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 coming 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.

4 Comments

Nice, I didn't know you could make a custom parser like that.
Ah, this is a great answer. I might consider this first--my answer makes you parse and then loop through the array, this answer simply parses.
@epascarello Am I correct that this would be more efficient than my solution because it only requires parsing rather than both parsing and then looping over the data?
I would assume so, but I do not know what the impact of the reviver is. Simple jsperf.com could determine it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.