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
)
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With