Javascript : Access JSON data example
Problem:
You have a JSON string such as below and you want to access the data individually via Javascript. How to access the JSON data with Javascript?
{
"name": "adamng",
"age": 38,
"address": {
"street": "108 Street",
"city": "Singapore"
},
"email": [{
"type": "personal",
"address": "adamng@somewherepersonal.com"
}, {
"type": "business",
"address": "adamng@someworkplace.com"
}]
}
Solution:
Use JSON.Parse()
to parse(process) the JSON string into a Javascript JSON Object and access the data via the JSON object.
Here you go!
Save this block of code into test.html
file and view it with your browser.
<html>
<script>
var JSONdata = '{"name": "adamng","age": 38,"address": {"street": "108 Street", "city": "Singapore" },"email": [{"type": "personal","address": "adamng@somewherepersonal.com"}, {"type": "business","address": "adamng@someworkplace.com"}]}';
var JSONObject = JSON.parse(JSONdata);
// retrieve the name
alert("Name :"+JSONObject["name"]);
alert(JSONObject.name);
// retrieve the age
alert(JSONObject["age"]);
alert(JSONObject.age);
alert(JSONObject.address.street);
alert(JSONObject["address"].city);
// access the first email object properties
alert(JSONObject.email[0].address);
// access the second email object properties
alert(JSONObject.email[1].type);
</script>
</html>
See also : Javascript : How to loop over and parse JSON data?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+14.2k Golang : How to filter a map's elements for faster lookup
+9.1k Golang : Play .WAV file from command line
+16.1k Golang : Find out mime type from bytes in buffer
+10.1k Golang : Convert file unix timestamp to UTC time example
+9.5k Golang : interface - when and where to use examples
+6.1k Golang : Selection sort example
+20.8k Golang : For loop continue,break and range
+14k Golang : How to pass map to html template and access the map's elements
+7.6k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+7.3k Golang : Detect sample rate, channels or latency with PortAudio