Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't map imported JSON data: TypeError thrown

Here’s sample data stored in data.json file:

[
  {"id": 23, "name": "Good!", "state": "OK"},
  {"id": 24, "name": "Not good...", "state": "Fail"},
  {"id": 26, "name": "Oh...", "state": "OK"},
  {"id": 27, "name": "What?", "state": "Fail"}
]

And this script tries to map the data:

import * as data from './data.json'

let jsonData = data
console.log(jsonData)

jsonData = jsonData.map(({name, state}) => ({name, state}))
console.log(jsonData)

The output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{default: Array(4)}
default
:
(4) [{...}, {...}, {...}, {...}]
0
:
(3) {id: 23, name: "Good!", state: "OK"}
1
:
(3) {id: 24, name: "Not good...", state:...}
2
:
(3) {id: 26, name: "Oh...", state: "OK"}
3
:
(3) {id: 27, name: "What?", state: "Fail...}
TypeError: jsonData.map is not a function
    at <anonymous>:35:21
    at dn (<anonymous>:16:5449)

So, the first console.log() call prints something that looks iterable for me. Why it throws the TypeError then?

I tried applying tricks like: let jsonData = JSON.parse(JSON.stringify(data)) but I couldn’t find anything that would work.

How to parse the data from the file to make it work with the map() method?

>Solution :

Congratulations! You finally bumped into the weird world of modules in JavaScript.

This here is probably what you want:

import data from './data.json'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading