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

jsonData ={name, state}) => ({name, state}))

The output is:

{default: Array(4)}
(4) [{...}, {...}, {...}, {...}]
(3) {id: 23, name: "Good!", state: "OK"}
(3) {id: 24, name: "Not good...", state:...}
(3) {id: 26, name: "Oh...", state: "OK"}
(3) {id: 27, name: "What?", state: "Fail...}
TypeError: 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'

Leave a Reply