48

How can I parse through a JSON file retrieving all its data and using it in my code?

I've tried importing the file and just tried console logging it, but all it does is print Object {}:

import jsonData from "./file.json";
console.log(jsonData);

This is what my file.json looks like:

[
    {
      "id": 1,
      "gender": "Female",
      "first_name": "Helen",
      "last_name": "Nguyen",
      "email": "[email protected]",
      "ip_address": "227.211.25.18"
    }, {
      "id": 2,
      "gender": "Male",
      "first_name": "Carlos",
      "last_name": "Fowler",
      "email": "[email protected]",
      "ip_address": "214.248.201.11"
    }
]

I'd want to be able to access the first and last name of each component and print those on the website.

1
  • this seemed to work for me as is
    – steff_bdh
    Commented Sep 10, 2019 at 3:49

5 Answers 5

42
var data = require('../../file.json'); // forward slashes will depend on the file location

var data = [
    {
      "id": 1,
      "gender": "Female",
      "first_name": "Helen",
      "last_name": "Nguyen",
      "email": "[email protected]",
      "ip_address": "227.211.25.18"
    }, {
      "id": 2,
      "gender": "Male",
      "first_name": "Carlos",
      "last_name": "Fowler",
      "email": "[email protected]",
      "ip_address": "214.248.201.11"
    }
];

for (var i = 0; i < data.length; i++)
{
    var obj = data[i];
    console.log(`Name: ${obj.last_name}, ${obj.first_name}`);
}

https://jsfiddle.net/c9wupvo6/

1
  • 2
    I am getting this error: Uncaught Error: Cannot find module "json!./Sections/file.json" even though that is the right path.
    – Parkicism
    Commented Jun 6, 2016 at 13:05
19

Applications packaged with webpack 2.0.0+ (such as those created with create-react-app) support imports from json exactly as in the question (see this answer.

Be aware that import caches the result, even if that result is parsed json, so if you modify that object, other modules that also import it have references to the same object, not a newly parsed copy.

To get a "clean" copy, you can make a function that clones it such as:

import jsonData from './file.json';

const loadData = () => JSON.parse(JSON.stringify(jsonData));

Or if you're using lodash:

import jsonData from './file.json';
import { cloneDeep } from 'lodash';

const loadData = () => cloneDeep(jsonData);
1
  • you need to put that json file inside src folder.
    – PostGrad
    Commented Jan 13, 2023 at 10:15
17

I also had problems with getting an empty Object back. Even when using require as suggested above.

fetch however solved my problem:

fetch('./data/fakeData.json')
  .then((res) => res.json())
  .then((data) => {
    console.log('data:', data);
  })

(As of today, the support isn't optimal though: http://caniuse.com/#feat=fetch)

4
  • 32
    This seems like it should work. But whenever I try it I get "localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" Commented Jul 25, 2017 at 20:16
  • how to make this work? the url generated for the fetch is incorrect. hence the jseals. error.
    – Community
    Commented Feb 7, 2020 at 8:26
  • 2
    @Community I've found a solution! Instead of passing the relative path, you need to pass the complete path(inside your project), like fetch("src/data/fakeData.json). Instead of using res.json(), use res.text(), and, in the last then, use JSON.parse(data)
    – reisdev
    Commented Feb 13, 2020 at 12:25
  • 1
    Thanks Muchachito - its getting there 💪 - just DONT FORGET to wrap this inside a useEffect or it wont work & also loop forever while failing
    – Sagive
    Commented Oct 20, 2022 at 0:20
4

For those of you who also have trouble with this, this code seemed to have fixed the problem

var jsonData = require('../../file.json');

class blah extends React.Component {

render(){
    var data; 

    function loadJSON(jsonfile, callback) {   

        var jsonObj = new XMLHttpRequest();
        jsonObj.overrideMimeType("application/json");
        jsonObj.open('GET', "../../file.json", true);
        jsonObj.onreadystatechange = function () {
              if (jsonObj.readyState == 4 && jsonObj.status == "200") {
                callback(jsonObj.responseText);
              }
        };
        jsonObj.send(null);  
     }

    function load() {

        loadJSON(jsonData, function(response) {
            data = JSON.parse(response);
            console.log(data);
        });
    }

    load();
}

}
1
  • 11
    This seems excessive for getting JSON into a local JS code, isn't there an easier solution?
    – Shazam
    Commented Jan 7, 2017 at 5:18
2

The JS spread operator also helps to get a deep copy of the object.

import jsonData from '../../file.json';

const loadData = [...jsonData];
2
  • 2
    The spread operator is a SHALLOW copy, not a deep one. The above would result in a new array, but the exact same object instances within it. Commented Feb 14, 2021 at 2:51
  • @EricHaynes is right
    – thodwris
    Commented Nov 29, 2021 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.