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
+8.2k Golang : On lambda, anonymous, inline functions and function literals
+47.9k Golang : Upload file from web browser to server
+8.6k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+11.9k Golang : Add ASCII art to command line application launching process
+31.6k Golang : Copy directory - including sub-directories and files
+21.7k Golang : Repeat a character by multiple of x factor
+4.1k Linux/MacOSX : Search and delete files by extension
+9.5k Golang : Find and replace data in all files recursively
+14.3k Golang : Search folders for file recursively with wildcard support
+16.2k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+12.6k Golang : Calculate elapsed years or months since a date