quantumpotato
quantumpotato

Reputation: 9767

JSON.parse works in console, but not when running script

So here's my text:

handleMyKeys(res) {
    // console.log(res);
    console.log("text" + this.responseText); //line 12
    let json = JSON.parse(this.responseText);
    console.log("Output is" + json.keys); //line 14
    console.log(window.mykeys);
    if (json.keys) {
      window.mykeys.setState({keys: json.keys});
    }

  }

And it prints out undefined for json.keys.

However when I run the same operation in console, I get a valid JSON object with .keys property. Why?

"{\"keys\":[\"itchio\",\"quantumitch\"]}"  MyKeys.js:12
Output isundefined  MyKeys.js:14
Object { props: Object, context: Object, refs: Object, updater: Object, _reactInternalFiber: Object, _reactInternalInstance: Object, state: Object }  MyKeys.js:15
x = "{\"keys\":[\"itchio\",\"quantumitch\"]}";
"{"keys":["itchio","quantumitch"]}"
JSON.parse("{\"keys\":[\"itchio\",\"quantumitch\"]}");
Object { keys: Array[2] }
y = JSON.parse("{\"keys\":[\"itchio\",\"quantumitch\"]}")
Object { keys: Array[2] }
y.keys
Array [ "itchio", "quantumitch" ]

Upvotes: 1

Views: 243

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97282

Based on your console output, it looks like your input has been encoded twice.

Compare the console output of the following two statements:

console.log("{\"keys\":[\"itchio\",\"quantumitch\"]}");
console.log("\"{\\\"keys\\\":[\\\"itchio\\\",\\\"quantumitch\\\"]}\"");

The output of the second command corresponds to what you're seeing in the console, indicating that the string that you're processing was escaped twice.

Check the content of the response you're receiving, or do a typeof JSON.parse(this.responseText) to verify.

Upvotes: 1

Kosh
Kosh

Reputation: 18413

Probably you have to write res or res.responseText instead of this.responseText. (depends on what res is.)

Upvotes: 0

Related Questions