Languages

JavaScript - how to access first element of JSON object array?

0 points
Asked by:
Reilly-Collier
860

I have s20_message which contains only one object.

var req = {
    s20_message: '[{"message":"incoming","uid":31227}]',
};

How do I access its message property?

1 answer
0 points
Answered by:
Reilly-Collier
860

Use [0] to access the first element, but in your case the s20_messages contains a string, not an array, so s20_messages[0] will just get you the first character - '['.

The solution would be to use JSON.parse() on the string first.

Practical example:

// ONLINE-RUNNER:browser;

var req = {
    s20_message: '[{"message":"incoming","uid":31227}]',
};

var s20_message = JSON.parse(req.s20_message);

var result = s20_message[0];

console.log(JSON.stringify(result)); // { message: 'incoming', uid: 31227 }

Note:

The JSON.stringify() method in this example was used only to print result object in the console.

 

References

  1. JSON.parse() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join