0

Currently I want to use the JSON data I fetched. My data looks like this:

{

"0": {
    "date": "2018-12-06T20:49:02.489000",
    "encoded": "B64Encoded",
    "height": "390",
    "name": "image2.jpg",
    "width": "390"
},
"1": {
    "date": "2018-12-06T20:49:02.489000",
    "encoded": "B64Encoded",
    "height": "136",
    "name": "index.jpg",
    "width": "371"
}
}

My problem lays in accessing the JSON Data. All then time, when I try

fetch('http://127.0.0.1:8888')
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({
            jsonData: responseJson[0].name
        })
    });

I end up with an undefined object. I believe the problem is in how the JSON is defined. How can I access it correctly?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
IPodFan
  • 91
  • 1
  • 9

1 Answers1

-1
fetch('http://127.0.0.1:8888')
.then((response) => response.json())
.then((responseJson) => {
    this.setState({
        jsonData: responseJson['0'].name
    })
});

notice the quotes '0' around the 0

yungbonesvillain
  • 661
  • 1
  • 5
  • 6
  • Try it yourself: `console.log({'0': 42}[0])` – Felix Kling Dec 06 '18 at 20:51
  • the syntax you have written is _never_ valid. try ```const obj = {'0': 42}; obj['0'] ``` – yungbonesvillain Dec 06 '18 at 21:02
  • The point of my comment was that it doesn't matter whether you use `[0]` or `['0']`. It's the same, hence it cannot solve the OP's problem. – Felix Kling Dec 06 '18 at 21:03
  • *"the syntax you have written is never valid."* Have you actually tried running `console.log({'0': 42}[0])` in your browser's console? It works: No syntax error and it prints `42`. So yes, it is valid. Not sure how else I can convince you. – Felix Kling Dec 06 '18 at 23:09