1

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.

2 Answers 2

4

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')
Sign up to request clarification or add additional context in comments.

1 Comment

I think you mean var, ES5 doesn't have let right?
2

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)
        });

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.