我怎样才能得到“__类型“;用javascript输入json

how can I get value of "__type" key in a json with javascript

本文关键字:javascript 输入 json 类型      更新时间:2023-09-26

解决方案:

我发现了问题,那就是手写笔解析器将函数重写为JSON,所以尽管ast像下面这样打印,但实际上ast对象没有__type属性,所以它导致了问题。


问题:

我正在使用手写笔ast树,它类似于:

{
"__type": "Root",
"nodes": [
  {
    "__type": "Ident",
    "name": "some-mixin",
    "val": {
      "__type": "Function",
      "name": "some-mixin",
      "lineno": 1,
      "column": 16,
      "params": {
        "__type": "Params",
        "nodes": [
          {
            "__type": "Ident",
            "name": "a",
            "val": {
              "__type": "Null"
            },
            "mixin": false,
            "lineno": 1,
            "column": 12
          },
          ...

它是一个用json表示的树。

并且我想要获得"__type"的值,但是使用["__type"]来获得该值,返回undefined。

"__type"在json中似乎有一些特殊的含义,我如何才能得到"__type"的值?

PS:我尝试了object.__type来获取值,但它不起作用。

此外,我发现了一些奇怪的东西

typeof ast // returns object

我使用JSON.stringfy(ast),字符串中有__type但我使用console.log(ast),__type丢失,我不知道为什么。。

我也试过

console.log(ast.hasOwnProperty('__type')) //return false

PPS:我在节点v0.12.0 中运行此代码

谢谢你的帮助!

"__type"不会以任何方式被JavaScript特别识别。验证AST是否已解析为对象。如果它仍然是一个JSON字符串,那么您将得到undefined。通过在AST上使用typeof运算符,您可以完全确定。它应该返回"object"而不是"string"。如果是"字符串",则必须使用JSON.parse

您可以尝试点表示法:

var x = {"__type": "Ident"};
console.log(x['__type']); // with 'string'
console.log(x.__type); // with 'dot'

JS中的"__type"没有什么特别之处。我会挑战性地测试的类型,以确保你正在处理一个对象。您的JSON对象有名称吗?您也可以尝试测试第一个对象。

nameOfYourObject['__type']
// if there are more than one
nameOfYourObject[0]['__type']

或者如果你正在进入物体:

nameOfYourObject.nodes[0]['__type']
// if there are more than one
nameOfYourObject[0].nodes[0]['__type']