Iman H
Iman H

Reputation: 476

JSON parser adds double quotes to object key in javascript

I have encountered a weird problem. I am consuming a RESTful API which returns the following response body:

{
"bourseMarket":[2.9966187229626504E16,2.8923052836886444E16],
"bourseTrade":[1.13589172355139E14,4.903299930043E13],
"‌bourseMarketf":[6.037694517655877E15,5.876172638826381E15],
"‌bourseTradef":[4.3646660180697E13,2.2708648590401E13]
}

When I parse this, JS returns the following object:

bourseMarket: Array [ 29966187229626504, 28923052836886444 ]
​bourseTrade: Array [ 113589172355139, 49032999300430 ]
​"‌bourseMarketf": Array [ 6037694517655877, 5876172638826381 ]
​"‌bourseTradef": Array [ 43646660180697, 22708648590401 ]

As you may see, JS adds double quotes to third and fourth object keys. And after that I can not refer to the object key and value:

TypeError: obj.bourseTradef is undefined

I even tried obj["bourseTradef"] but was unsuccessful too.

I use standard methods to retrieve data:

const getData = async (url) => {

    return await fetch(url).then(resp => {
        if (resp.status === 200) {

            return resp.json();
        }
        else
            throw new Error("HTTP ERROR");
    }
    ).catch(e => { showAlert("مشکل در شبکه") });
}

getData(tradeBaseUrl).then((obj) => {
        console.log(obj);
....

UPDATE

I made a stupid mistake. I have added an invisible character at the beginning of those two keys mistakenly. I found out the problem by inspecting the request body Network section, as Phil suggested. Two little pink circles were added at the beginning of key strings.

Upvotes: 0

Views: 765

Answers (2)

seanpue
seanpue

Reputation: 323

There is a zero width non-joiner (\u200c) character at the start of "‌bourseMarketf" and "‌bourseTradef" in the sample. Javascript adds the quotation marks to indicate its presence.

Upvotes: 1

KooiInc
KooiInc

Reputation: 122906

Both keys contain a hidden character. If you open (edit) the snippet it shows, but you can also use charCodeAt to reveal it:

const x = JSON.parse(`{
  "bourseMarket":[2.9966187229626504E16,2.8923052836886444E16],
  "bourseTrade":[1.13589172355139E14,4.903299930043E13],
  "‌bourseMarketf":[6.037694517655877E15,5.876172638826381E15],
  "‌bourseTradef":[4.3646660180697E13,2.2708648590401E13]
}`);

console.log(`you would expect "bourseTradef".charCodeAt(0) to be  be ${"bourseTradef".charCodeAt(0)}`);
console.log(`but here it is ${"‌bourseTradef".charCodeAt(0)}`);

console.log(`So x["‌bourseTradef"] is possible: ${x["‌bourseTradef"]}`);
console.log(`But not x["bourseTradef"]: ${x["bourseTradef"]}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 3

Related Questions