React lives in JavaScript. So parsing a JSON string is done with:
var myObject = JSON.parse(myjsonstring);
How to fetch a file from somewhere with AJAX is a different question.
You could use fetch() for this. See for example
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or
https://davidwalsh.name/fetch or
https://blog.gospodarets.com/fetch_in_action
Having problem in parsing the JSON data using react.js
Parsing JSON from API Response
How can I parse through local JSON file in React js?
reactjs - Parse content of json in React - Stack Overflow
Videos
» npm install react-json-parser
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/
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);