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
+10.6k Golang : Simple File Server
+9.5k Golang : Accessing content anonymously with Tor
+5.9k Golang : Use NLP to get sentences for each paragraph example
+20.3k Golang : Determine if directory is empty with os.File.Readdir() function
+10.9k Golang : Removes punctuation or defined delimiter from the user's input
+14.5k How to automatically restart your crashed Golang server
+6.1k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+24.6k Golang : How to validate URL the right way
+6.3k Golang : Detect face in uploaded photo like GPlus
+11.5k CodeIgniter : Import Linkedin data
+7.2k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+10.9k Golang : Get UDP client IP address and differentiate clients by port number