I have the following json structure returned by an API:
{
"data": {
"artemis_ids": {},
"symbols": {
"0XBTC": {
"price": 2.37
}
}
}
}
When I use JSON.parse in Google apps script, the "0XBTC" string is somehow converted to number 11. See below the results of console.log:
console.log("content", content);
console.log("content json", JSON.parse(content));
Any idea why this is happening and how to solve it?
var content = `
{
"data": {
"artemis_ids": {},
"symbols": {
"0XBTC": {
"price": 2.37
}
}
}
}
`;
console.log("content", content);
console.log("content json", JSON.parse(content));
2
Answers
I think it is not a code issue, because it runs well at node@18 and Chrome@latest.
Modification points:
From
content json {data={artemis_ids={}, symbols={11={price=2.37}}}}
, your showing log, I guessed that you might disable the V8 runtime with the script editor. But, when the V8 runtime is disabled, the backticks cannot be used. From this situation, also I guessed that your showing snippet might not be your actual script.By supposing that my guess is correct, I tested the following sample script. And, I disabled the V8 runtime with the script editor.
When this script is run without V8 runtime, the following result is obtained.
I confirmed that
console.log("content json", JSON.parse(content))
showscontent json {data={artemis_ids={}, symbols={11={price=2.37}}}}
. If my guess is correct, I think that this might be the reason for your current issue.And also, when I tested the following script.
console.log(sample1)
andconsole.log(sample2)
are as follows.and
From this situation, I guessed that this situation might be a bug or the current specification of Google Apps Script without V8 runtime. But, in the current stage, when the V8 runtime is disabled with the script editor,
"runtimeVersion": "DEPRECATED_ES5"
is added to the manifest file (appsscript.json
). RefIn order to avoid this situation, as a simple solution, please enable V8 runtime with the script editor. Ref
By this, the above script
sample()
returns as follows.and
0XBTC
is correctly used as the key.Note:
If you are required to use your script by disabling the V8 runtime, how about using polyfill of JSON.parse? Ref When this is reflected in a sample script, it becomes as follows.
References: