JavaScript JSON.parse“0x”string strange conversion

polhcujo  于 2023-08-08  发布在  Java
关注(0)|答案(2)|浏览(87)

我有一个API返回的json结构:

{
    "data": {
        "artemis_ids": {},
        "symbols": {
            "0XBTC": {
                "price": 2.37
            }
        }
    }
}

字符串
当我在Google apps脚本中使用JSON.parse时,“0XBTC”字符串以某种方式转换为数字11。下面是console.log的结果:

console.log("content", content);
console.log("content json", JSON.parse(content));


的数据
你知道为什么会发生这种情况以及如何解决吗?

var content = `
    {
        "data": {
            "artemis_ids": {},
            "symbols": {
                "0XBTC": {
                    "price": 2.37
                }
            }
        }
    }
`;

console.log("content", content);
console.log("content json", JSON.parse(content));

svgewumm

svgewumm1#

修改要点:

content json {data={artemis_ids={}, symbols={11={price=2.37}}}}(您的显示日志)中,我猜测您可能会使用脚本编辑器禁用V8运行时。但是,当V8运行时被禁用时,反引号就不能使用了。从这种情况下,我也猜测,您的显示片段可能不是您的实际脚本。
假设我的猜测是正确的,我测试了以下示例脚本。而且,我用脚本编辑器禁用了V8运行时。

function myFunction() {
  var content = '{"data":{"artemis_ids":{},"symbols":{"0XBTC":{"price":2.37}}}}';

  console.log("content", content);
  console.log("content json", JSON.parse(content));
}

字符串
在没有V8运行时的情况下运行此脚本时,将获得以下结果。
x1c 0d1x的数据
我确认console.log("content json", JSON.parse(content))显示content json {data={artemis_ids={}, symbols={11={price=2.37}}}}。如果我的猜测是正确的,我认为这可能是你目前问题的原因。
而且,当我测试下面的脚本时。

function sample() {
  var content = '{"data":{"artemis_ids":{},"symbols":{"0XBTC":{"price":2.37}}}}';

  var sample1 = JSON.stringify(JSON.parse(content));
  var sample2 = Object.keys(JSON.parse(content).data.symbols);

  console.log(sample1);
  console.log(sample2);
}


console.log(sample1)console.log(sample2)如下。

{"data":{"artemis_ids":{},"symbols":{"11":{"price":2.37}}}}


和/或

[11]


从这种情况来看,我猜测这种情况可能是一个bug,或者是没有V8运行时的Google Apps Script的当前规范。但是,在当前阶段,当使用脚本编辑器禁用V8运行时,"runtimeVersion": "DEPRECATED_ES5"被添加到清单文件(appsscript.json)。参考文献

**为了避免出现这种情况,简单的解决方法是使用脚本编辑器开启V8运行时。**参考



这样,上面的脚本sample()返回如下。

{"data":{"artemis_ids":{},"symbols":{"0XBTC":{"price":2.37}}}}


和/或

[ '0XBTC' ]


0XBTC被正确地用作密钥。

注:

如果需要通过禁用V8运行时来使用脚本,那么使用JSON.parse的polyfill如何?Ref当这反映在示例脚本中时,它变成如下所示。

function sample2() {
  // Ref: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#%E3%83%9D%E3%83%AA%E3%83%95%E3%82%A3%E3%83%AB
  var rx_one = /^[\],:{}\s]*$/;
  var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
  var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  JSON.parse = function (text, reviver) {

    // The parse method takes a text and an optional reviver function, and returns
    // a JavaScript value if the text is a valid JSON text.

    var j;

    function walk(holder, key) {

      // The walk method is used to recursively walk the resulting structure so
      // that modifications can be made.

      var k;
      var v;
      var value = holder[key];
      if (value && typeof value === "object") {
        for (k in value) {
          if (Object.prototype.hasOwnProperty.call(value, k)) {
            v = walk(value, k);
            if (v !== undefined) {
              value[k] = v;
            } else {
              delete value[k];
            }
          }
        }
      }
      return reviver.call(holder, key, value);
    }

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.

    text = String(text);
    rx_dangerous.lastIndex = 0;
    if (rx_dangerous.test(text)) {
      text = text.replace(rx_dangerous, function (a) {
        return (
          "\\u" +
          ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
        );
      });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with "()" and "new"
    // because they can cause invocation, and "=" because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.

    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
    // replace all simple value tokens with "]" characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or "]" or
    // "," or ":" or "{" or "}". If that is so, then the text is safe for eval.

    if (
      rx_one.test(
        text
          .replace(rx_two, "@")
          .replace(rx_three, "]")
          .replace(rx_four, "")
      )
    ) {

      // In the third stage we use the eval function to compile the text into a
      // JavaScript structure. The "{" operator is subject to a syntactic ambiguity
      // in JavaScript: it can begin a block or an object literal. We wrap the text
      // in parens to eliminate the ambiguity.

      j = eval("(" + text + ")");

      // In the optional fourth stage, we recursively walk the new structure, passing
      // each name/value pair to a reviver function for possible transformation.

      return (typeof reviver === "function") ?
        walk({
          "": j
        }, "") :
        j;
    }

    // If the text is not JSON parsable, then a SyntaxError is thrown.

    throw new SyntaxError("JSON.parse");
  };

  var content = '{"data":{"artemis_ids":{},"symbols":{"0XBTC":{"price":2.37}}}}';

  var sample1 = JSON.stringify(JSON.parse(content));
  var sample2 = Object.keys(JSON.parse(content).data.symbols);

  console.log(sample1); // <--- {"data":{"artemis_ids":{},"symbols":{"0XBTC":{"price":2.37}}}}
  console.log(sample2); // <--- [0XBTC]
}

sample2();

参考文献:

ewm0tg9j

ewm0tg9j2#

我认为这不是代码问题,因为它在node@18和Chrome@latest上运行良好。
x1c 0d1x的数据

相关问题