Reputation: 109
I have a local JSON file , I want to parse it into an Object to get manipulated in React for a website of reviews.
I have tried to use two approach, the first one I copy the file into a .js file and declare the data in the JSON file as array and try to use code to parse it into object. My other attempts was to read the files and use parse directly both of them did not work. Is anyone who can advice me on the best way to tackle this?
const fs = require('fs');
var fileString = fs.readFileSync('./restaurant.json').toString();
var fileObj = JSON.parse(fileString);
var restaurants = fileObj.restaurant;
let restaurants = data.map((item) => {
let res = (item.isArray())? map((input)=>JSON.parse(input)):
JSON.parse(item)
return res;
});
export default restaurants;
should generate object of details on restaurants and comments made.
Upvotes: 1
Views: 426
Reputation: 1758
If it's a local file in your code you can just import it directly. The JSON will get converted to an object for you.
import {restaurants} from './restaurant.json'
or for ES5
var restaurants = require('./restaurant.json')
Upvotes: 4
Reputation: 342
You have a few errors in you function calling. I dont know your data structure. May that will help
const fs = require('fs');
var fileString = fs.readFileSync('./restaurant.json').toString();
var fileObj = JSON.parse(fileString);
var data = fileObj.restaurant;
let restaurants= data.map((item)=>{
return (item.isArray())?item.map((input)=>JSON.parse(input)):JSON.parse(item)
});
Upvotes: 2