
In many technical interview, you would be asked to parse JSON file.
JSON stands for JavaScript Object Notation. If you’ve ever used a web app, there’s a very good chance that it used JSON to structure, store, and transmit data between its servers and your device.
Read More About Interview Prep Guide.
JSON objects vs JavaScript Object Literals
Here is the Example of JSON object.
const cityData = '{ "city":"LosAngeles", "state":"california", "zipcode":"09768"}';
Read More on How to Parse JSON.
And Here is the example of JSON Object.
const cityData = {
city: 'LosAngeles',
state: 'california',
zipcode: 09768
}
Fetch API to get JSON data from API endpoint.
fetch('https://api.chucknorris.io/jokes/random?category=dev')
.then(res => res.json()) // the .json() method parses the JSON response into a JS object literal
.then(data => console.log(data));
JSON arrays vs JavaScript arraysJSON arrays work pretty much the same way as arrays in JavaScript, and can contain strings, booleans, numbers, and other JSON objects. For example:
[
{
"name": "Jane Doe",
"favorite-game": "Stardew Valley",
"subscriber": false
},
{
"name": "John Doe",
"favorite-game": "Dragon Quest XI",
"subscriber": true
}
]
Here's what that might look like in plain JavaScript:
const profiles = [
{
name: 'Jane Doe',
'favorite-game': 'Stardew Valley',
subscriber: false
},
{
name: 'John Doe',
'favorite-game': 'Dragon Quest XI',
subscriber: true
}
];
Read more about Interview Prep Guide.
JSON as a string
For example, when you write JSON in a separate file like with jane-profile.json or profiles.json above, that file actually contains text in the form of a JSON object or array, which happens to look like JavaScript.
And if you make a request to an API, it’ll return something like this:
{"name":"Jane Doe","favorite-game":"Stardew Valley","subscriber":false}
Fortunately, JavaScript includes a super helpful method to do just that – JSON.stringify()
:
const newJoke = {
categories: ['dev'],
value: "Chuck Norris's keyboard is made up entirely of Cmd keys because Chuck Norris is always in command."
};
<!-- wp:paragraph -->
<p>Here are the examples how to parse JSON using Vanilla Javascript.</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code><script>
const txt = '{"name":"John", "age":30, "city":"New York"}'
const obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>
</code></pre>
<!-- /wp:code -->
<!-- wp:paragraph -->
<p>JSON Array Example:</p>
<!-- /wp:paragraph -->
<!-- wp:code -->
<pre class="wp-block-code"><code><script>
const text = '[ "Ford", "BMW", "Audi", "Fiat" ]';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr[0];
</script>
</code></pre>
<!-- /wp:code -->