# Reading JSON Files
Just like XML files, we can use JavaScript to fetch remote JSON files from a web server and then use the contents of those files as the data to drive our application. Next week we will cover the details on the fetching of the data files with AJAX.
Once we have the file back we will be given the contents of the JSON file as a STRING
, not an actual JavaScript Object. We need to convert the string into an object. This is a achieved with the JSON
object.
let dataObject = JSON.parse(stringFromFile);
In the example above dataObject will now be an actual object that we can use in our code. We can read it's properties and loop through its arrays.
Let's say we have this JSON data in our dataObject variable:
{
"movies": [
{
"id": "tt0295297",
"title": "Harry Potter and the Chamber of Secrets",
"imdb-url": "http://www.imdb.com/title/tt0295297/",
"characters": [
{ "name": "Harry Potter", "actor": "Daniel Radcliffe" },
{ "name": "Hermoine Grainger", "actor": "Emma Watson" },
{ "name": "Ron Weasley", "actor": "Rupert Grint" }
]
}
]
}
2
3
4
5
6
7
8
9
10
11
12
13
14
It's similar to the data we were using in our XML example, except that it is a lot more condensed. We don't have opening and closing tags. The list of characters is just an array of objects. The movies property is an array it is also a top level property of our dataObject variable.
To loop through our list of characters for this movie and console log out the actor's names:
let movie = dataObject.movies[0];
console.log("Characters in", movie.title);
//movie is the first movie in the movies Array
//which holds a characters Array
movie.characters.forEach(function(char) {
console.log(char); //this will output the name of each character
});
2
3
4
5
6
7
Notice that I added the declaration and assignment of numChars inside the initialization area of our for loop. This way it only exists during the loop and only gets calculated once.
It is the same effect as with the XML, just less code.
# Looping through Objects
If you needed to loop through all the properties in the first movie but didn't know the names of the properties then we can use the for..in loop.
let movie = dataObject.movies[0];
for (let prop in movie) {
console.log("Property name is", prop);
console.log("Property value is", movie[prop]);
}
2
3
4
5
We just use the square bracket syntax instead of the dot notation. This way we can use the variable as the property name.
# Stringify
If you ever need to convert a JavaScript object into a string, there is also a stringify method.
let strData = JSON.stringify(dataObject);