How to parse a JSON file in JavaScript?

In JavaScript, you can parse a JSON file using the JSON.parse() method. Here is a sample JSON file:

{
    "name": "John Doe",
    "age": 32,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA"
    }
}

Here is some sample code that uses the Node.js-based fs module's readFile method to load the above file from disk and then uses the JSON.parse method to parse it into a JavaScript object:

var fs = require('fs');

fs.readFile('file.json', 'utf-8', function (err, data) {
    if (err) throw err;

    var obj = JSON.parse(data);

    console.log(obj);
});

If you want to parse a JSON string in the browser, you can use the same JSON.parse method. However, if you are using the fetch API to load a remote file/API, you can simply use the json method of the response object. Here is an example:

<script>
    fetch('http://httpbin.org/ip')
        .then(res => res.json())
        .then((data) => {
            console.log(data);
        }).catch(err => console.error(err));
</script>

Related JSON web scraping questions: