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
+22.2k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+10k Golang : Detect number of active displays and the display's resolution
+5.6k Unix/Linux : How to archive and compress entire directory ?
+9.6k Golang : Generate EAN barcode
+7.1k Golang : Normalize email to prevent multiple signups example
+12.5k Golang : Display list of countries and ISO codes
+32.5k Golang : Validate email address with regular expression
+11.3k Google Maps URL parameters configuration
+8.5k Golang : Count leading or ending zeros(any item of interest) example
+4.9k Adding Skype actions such as call and chat into web page examples
+5.6k Unix/Linux/MacOSx : How to remove an environment variable ?
+5.9k Unix/Linux : How to test user agents blocked successfully ?