Hey all,
I'm having a bit of a drama getting values out of some JSON - so wondering if someone could please help. I've got a dummy web service set up on my PC and running the simulator. My JSON response looks like this:
{"Id":10,"Name":"Leo Messi"}
This returns the first value OK:
let msg = JSON.parse(evt.data.Id);
but this doesn't return the second:
let msg = JSON.parse(evt.data.Name);
Any thoughts? Is my JSON not good, or am I missing something in the parsing?
Cheers,
Tim
Best AnswerI think, perhaps, you are trying to do too much in one go. As I understand it, JSON.parse() converts a JSON-formatted string into a javascript object. Then, you can use normal javascript notation to access that object's contents. Try (untested):
let obj = JSON.parse(evt.data); let msg = obj.Name;
You could probably do this in one expression, but it may be more efficient and clearer not to.
Hi,
I think it was my mistake. The object itself was already an object and not a JSON string, so I was able to use:
let msg = evt.data.Message;
Instead of having to parse it first.
Thanks anyway!
Cheers,
Tim
Best Answer