06-29-2018 19:44
06-29-2018 19:44
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
06-29-2018 20:01
06-29-2018 20:01
I 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.
07-01-2018 20:46
07-01-2018 20:46
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
07-03-2018 09:38
07-03-2018 09:38
The JSON.parse returns an object so it should be something like
let obj = JSON.parse(evt.data.Id);
console.log(`id: ${obj.id}`);
console.log(`name: ${obj.name}`);