Home > Blockchain >  Can't map imported JSON data: TypeError thrown
Can't map imported JSON data: TypeError thrown

Time:01-13

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:

{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?

CodePudding user response:

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

This here is probably what you want:

import data from './data.json'
  • Related