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": "[email protected]"
}, {
"type": "business",
"address": "[email protected]"
}]
}
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": "[email protected]"}, {"type": "business","address": "[email protected]"}]}';
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
+31.7k Golang : Validate email address with regular expression
+15.2k Golang : Force download file example
+32k Golang : Copy directory - including sub-directories and files
+9k Golang : How to get username from email address
+39.7k Golang : Convert to io.ReadSeeker type
+13.4k Golang : Tutorial on loading GOB and PEM files
+16.1k Golang : Convert slice to array
+13.1k Golang : Increment string example
+38.8k Golang : How to iterate over a []string(array)
+13.7k Golang : Compress and decompress file with compress/flate example
+22.7k Golang : Read a file into an array or slice example
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example