0

Can someone help me with this json {"event":"update","data":"{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}, how parse this values from json 55.5 and 5.3744. I will be grateful for help.

Noob
  • 3
  • 1
  • 1
    Possible duplicate of [Parse JSON in JavaScript?](https://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Biffen Aug 15 '18 at 12:57

1 Answers1

0

Your JSON is invalid and cannot be parsed.

I assume your data is a JSON string within a JSON string that should be parsed after the main JSON string has been parsed. This is not really efficient and you should consider not stringifying the data value in the first place.

Your JSON should look like this:

{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}

Or:

{\"event\":\"update\",\"data\":{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}

In JavaScript:

const json = '{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}';
const obj = JSON.parse(json);
const val1 = obj.data.asks[0][0];
const val2 = obj.data.asks[0][1];

If you must have data as a JSON encoded string, encode it correctly. If you want to know what your JSON string should look like in this case, work backwards:

const dataString = JSON.stringify({
    asks: [
        ["55.5", "5.3744"],
        ["55.74","0.8087"]
    ]
});

const jsonString = JSON.stringify({
    event: "update",
    data: dataString
});

// {\"event\":\"update\",\"data\":\"{\\\"asks\\\":[[\\\"55.5\\\",\\\"5.3744\\\"],[\\\"55.74\\\",\\\"0.8087\\\"]]}\"}

// And back again...

const asks = JSON.parse(
    JSON.parse(jsonString).data
).asks;
const val1 = asks[0][0];
const val2 = asks[0][1];
Nick
  • 2,576
  • 1
  • 23
  • 44