Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object Parsing

I am attempting to parse javascript (using javascript), and I've run into a problem with objects. How does javascript determine the difference between an object or a block?

For instance

{ x : 1, y : 2}

Token Stream:

[{][x][:][1][,][y][:][2][}]

Is clearly an object, however

{ var x = 1; var y = 2}

Token Stream:

[{][var][x][=][1][;][var][y][=][2][}]

Is a perfectly valid anonymous javascript block. How would I go about efficiently identifying each token stream as an object or block?

However, more important then both of these how would I determine the difference between a token stream that could be an object or a block like the following:

{ a : null }

Token Stream:

[{][a][:][null][}]

This could either be an object whose parameter a is equal to null, or it could be a block where the first statement in the block (null) has a label (a)

like image 854
GAgnew Avatar asked Nov 11 '11 04:11

GAgnew


People also ask

How do you parse an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is parsing in JavaScript?

Parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the JavaScript engine inside browsers. The browser parses HTML into a DOM tree.

What does JSON parse do in JavaScript?

JSON.parse() The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is JSON () method?

The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .


1 Answers

You don't.

The context of the syntax affects it's identity. You can't just pluck things out of context and determine what they are.

In the grammar, an object literal is:

'{' (propertyNameAndValueList)? '}'

whereas a block is:

'{' (statementList)? '}'

But literals only exist where expressions are allowed, while blocks exist where statements are allowed. And those aren't the same thing.

So, it's the surrounding context that distinguishes the two forms.

like image 68
Will Hartung Avatar answered Jan 20 '23 13:01

Will Hartung