10

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.

36
  • 1
    Complaining about what exactly? Commented Feb 4, 2019 at 17:45
  • 1
    Export is an ES6 Feature and not a feature of JSON, JSON is a different standard to ES6, rfc7159 Commented Feb 4, 2019 at 17:45
  • 1
    Please provide a Minimal, Verifiable, Complete example. See this: stackoverflow.com/help/mcve Commented Feb 4, 2019 at 17:46
  • I have updated the code to just demonstrate what I am trying to do, basically I'd like to make the data from this file be available to be imported into another file in a variable e.g. "import sample from 'sample.json' Commented Feb 4, 2019 at 17:54
  • 1
    @jobe: Or did you determine “no data” from console.log(data.id) producing undefined? It should be data[0].id, since the export is an array. Commented Feb 4, 2019 at 18:23

2 Answers 2

8

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

export const data = ...some data

at required place

import {data} from '../filepath'
Sign up to request clarification or add additional context in comments.

6 Comments

How is then imported to be used in another file? I tried this method also but none of the data then appears in the other file? How would the import statement look if both files are in the same folder?
Is it possible to do this in es6 using modules and import statements? I thought they can be used instead of require statements. This is the exact problem though.
@jobe yes it can be all we need is to setup transpiler. i am not familiar with REPL but wait let me try to do it
ok - I am reading some other posts too.
|
-1

One workaround for the default HTML standard prohibition of importing files not served as */javascript is to use fetch() to get the file, then export the result as default and import a data URL

<script type="module">
  (async() => {
    let {default:sample} = await import(`data:application/javascript,${encodeURIComponent('export default ')}${JSON.stringify(await(await fetch('file.json')).json())}`);
    console.log(sample);
  })()
</script>

plnkr

See also ES6 modules in local files - The server responded with a non-JavaScript MIME type

11 Comments

@guest271314 I will try that but a developer friend of mine mentioned not having to change the file extension to make it work - it does work the way you're suggesting but I'm trying to see if the JSON extension method will work.
@jobe Failed to load module script: The server responded with a non-JavaScript MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec. Did your "developer friend" share working code with you to prove their claim?
@guest271314 No he didn't it was meant to be my learning exercise to make it work. He did show me a working version with a JSON file but not in detail.
@KamilKiełczewski How do you propose to include export in a valid JSON file?
@guest271314 Thanks for your answer, I'm trying to find a way to do it with a JSON file extension.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.