Parsing JSON Files in JavaScript

  • Author
    by Josselin Liebe
    a month ago
  • In JavaScript, you can parse a JSON file using the JSON.parse() method. Below is a sample JSON file:

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

    Here’s some example code that uses Node.js's fs module with the readFile method to load the JSON file from disk and then parses it into a JavaScript object using JSON.parse():

    const fs = require('fs');
    
    

    fs.readFile('file.json', 'utf-8', (err, data) => { if (err) throw err; const obj = JSON.parse(data); console.log(obj); });

    If you want to parse a JSON string in the browser, you can also use JSON.parse. However, if you're loading a remote file or API using the fetch API, you can directly use the json method of the response object. Here’s an example:

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

    In this example, the fetch API loads the JSON response, which is then parsed with res.json() before being logged to the console.