1

Solution:

I found the problem, that is stylus parser rewrite the function toJSON, so although the ast print like following, but actually ast object don't have __type property, so it causes the problem.


Question:

I am using stylus ast tree which is like :

{
"__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
          },
          ...

it's a tree expressed by json.

and I want to get value of "__type", but using ["__type"] to get the value, undefined is returned.

it seems like "__type" has some special meaning in json, how can I get the value of "__type"?

PS: I tried object.__type to get the value, it doesn't work.

In addition, I found some weird thing

typeof ast // returns object

I use JSON.stringify(ast), and __type is in the string But I use console.log(ast), __type is missing, I don't know why..

And also I tried

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

PPS: I run this code in node v0.12.0

Thanks for your help!

Yiting Li
  • 13
  • 4

3 Answers3

0

"__type" is not specially recognized in any way by JavaScript. Verify that the AST has been parsed to an object. If it is still a JSON string, you'll get undefined. You can be absolutely sure by using the typeof operator on your AST. It should return "object" rather than "string". If its "string" then you have to use JSON.parse.

Andy Carlson
  • 3,633
  • 24
  • 43
0

you could try dot notation:

var x = {"__type": "Ident"};

console.log(x['__type']); // with 'string'
console.log(x.__type); // with 'dot'
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

there is nothing special about "__type" in JS. I would defiantly test the typeof to insure that you are dealing with an object. Does your JSON object have a name? You can also try this to test the first object.

nameOfYourObject['__type']

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

or if you are reaching into the object:

nameOfYourObject.nodes[0]['__type']

// if there are more than one
nameOfYourObject[0].nodes[0]['__type']
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12