Javascript JSON parse SyntaxError: Unexpected token o in JSON at position 1

I am sending a json string from flask using flask.jsonify(myobject=myobject)

On the client in in Firefox webconsole network monitor I can see network response JSON :

myobj: {"date": {"0":"2018-03-10T00:00:00.000Z","1":"2018-03-11T00:00:00.000Z","2":"2018-03-12T00:00:00.000Z"},"value":{"0":18.45,"1":10.11,"2":16.16}}

in chrome:

"myobj": "{\"date\":{\"0\":\"2018-03-10T00:00:00.000Z\",\"1\":\"2018-03-11T00:00:00.000Z\",\"2\":\"2018-03-12T00:00:00.000Z\"},\"value\":{\"0\":18.45,\"1\":10.11,\"2\":16.16}}"

I am trying to read this object using:

var data = JSON.parse(JSON.stringify(myobj))

I get the following error:

error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

and I also tried:

var data = JSON.parse(JSON.stringify(myobj))

I get the following error:

error: SyntaxError: Unexpected token o in JSON at position 1

When I use

for (var key in myobj) {
    console.log(myobj[key])
}

I get each character printed on a new line.

I realise a similar qq may have been asked before but I cant work this out

Any ideas

2 answers

  • answered 2018-03-11 13:43 connexo

    Remove the inner call to JSON.stringify. The response you get is already a valid JSON String.

    let myobj = "{\"date\":{\"0\":\"2018-03-10T00:00:00.000Z\",\"1\":\"2018-03-11T00:00:00.000Z\",\"2\":\"2018-03-12T00:00:00.000Z\"},\"value\":{\"0\":18.45,\"1\":10.11,\"2\":16.16}}"
    
    console.log(JSON.parse(myobj))

  • answered 2018-03-11 13:48 King Rui

    Please remove "myobj": in your response body, just "{\"date\":{\"0\":\"2018-03-10T00:00:00.000Z\",\"1\":\"2018-03-11T00:00:00.000Z\",\"2\":\"2018-03-12T00:00:00.000Z\"},\"value\":{\"0\":18.45,\"1\":10.11,\"2\":16.16}}" is enough.

    var myobj = "{\"date\":{\"0\":\"2018-03-10T00:00:00.000Z\",\"1\":\"2018-03-11T00:00:00.000Z\",\"2\":\"2018-03-12T00:00:00.000Z\"},\"value\":{\"0\":18.45,\"1\":10.11,\"2\":16.16}}";
    console.log(JSON.parse(myobj));