Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export an array of objects in a JSON file and then import using es6 [duplicate]

I have an array of objects in a json file. I'm trying to import this file into another file so I can reference the data in a simple react project.

I've tried various combinations of export default and named exports but the JSON file is always complaining when I save it. Here is what I am trying to achieve:

(File1.json)

    [
      {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
    ]

File2.js

import data from '.\file1.json'

console.log(data.id);

The issue I'm having is that I see no errors in my JS file but the data.id value isn't being displayed. However in my JSON file, I am having problems exporting it to use.

Question: How to import ".json" file (not ".js") with objects file using es6?

Update I've managed to make it work in the create-react-app environment, I left the json file as an array of objects, then in the js file I used "import xyx from './xyz';"

This worked for me, this answer isn't mentioned in the duplicate marked post so I think it should have it's own answer - hopefully this helps someone else.

like image 542
j obe Avatar asked Feb 04 '19 17:02

j obe


People also ask

How do I convert a JSON object to an array?

Approach 1: First convert the JSON string to the JavaScript object using JSON. Parse() method and then take out the values of the object and push them into the array using push() method.


1 Answers

Since you're storing as JSON extension you should not use export const data = ...

You should directly store the data

xyz.json

[
      {
        "userId": 1,
        "id": 1,
        "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
      }
    ]

JSON

For demo you can see this

Or you can set extension to .js

const export data = ...some data

at required place

import {data} from '../filepath'
like image 163
Code Maniac Avatar answered Oct 30 '22 06:10

Code Maniac