nodejs REPL doesn't process JSON.parse()? - javascript

I'm trying node with REPL, parsing from string failed like this:
$node
> var str="{'a':1,'b':2}"
undefined
> var js=JSON.parse(str)
SyntaxError: Unexpected token ' in JSON at position 1
But the reversed parse seems OK:
> var json = {a : ' 1 ',b : ' 2'};
undefined
> var str = JSON.stringify(json);
undefined
> str
'{"a":" 1 ","b":" 2"}'
Where did I get wrong?

You have syntax error in your JSON:
{'a':1,'b':2}
^
|
'--- invalid syntax. Illegal character (')
JSON is not the same thing as Javascript object literals. JSON is a file/data format which is compatible with object literal syntax but is more strict. The JSON format was specified by Douglas Crockford and documented at http://json.org/
Some of the differences between JSON and object literals:
Property names are strings
Strings start and end with double quotes (")
Hexadecimals numbers (eg. 0x1234) are not supported
etc.

Related

Parse Complex Json String

I'm attempting to parse the following JSON string (not in control of the format, I know it's hideous).
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
obj = JSON.parse(json);
I'm getting Error: Unexpected token w in JSON at position 43 which is where the first value of nestedjsonstr begins. Is there any elegant way to parse this?
Maybe this can help you out. You replace the curly braces inside your string without the ", and remove the \.
var json = '{"what.1.does":"anything", "nestedjsonstr":"{\"whatup\":\"nada\"}"}';
json = json.replace('\"{', '{').replace('}\"', '}').replace('\\"', '"');
obj = JSON.parse(json);
console.log(obj);

ANTLR4 JavaScript parser: how to catch an error in parsing

I have a grammar in ANTLR4 around which I am writing an application. A snippet of the pertinent grammar is shown below:
grammar SomeGrammar;
// ... a bunch of other parse rules
operand
: id | literal ;
id
: ID ;
literal
: LITERAL ;
// A bunch of other lexer rules
LITERAL : NUMBER | BOOLEAN | STRING;
NUMBER : INTEGER | FLOAT ;
INTEGER : [0-9]+ ;
FLOAT : INTEGER '.' INTEGER | '.' INTEGER ;
BOOLEAN : 'TRUE' | 'FALSE' ;
ID : [A-Za-z]+[A-Za-z0-9_]* ;
STRING : '"' .*? '"' ;
I generate the antlr4 JavaScript Lexer and Parser like so:
$ antlr4 -o . -Dlanguage=JavaScript -listener -visitor
and then I overload the exitLiteral () prototype to check if an operand is a literal. The issue is that if I pass
a
it (force) parses it to a literal, and throws an error (e.g. below shown with grun):
$ grun YARL literal -gui -tree
a
line 1:0 mismatched input 'a' expecting LITERAL
(literal a)
The same error when I use the JavaScript Parser which I overloaded like so:
SomeGrammarLiteralPrinter.prototype.exitLiteral = function (ctx) {
debug ("Literal is " + ctx.getText ()); // Literal is a
};
I would like to catch the error so that I can decide that it is an ID, and not a LITERAL. How do I do that?
Any help is appreciated.
Better solution is to adjust the grammar so that it accurately describes the intended syntax to begin with:
startRule : ruleA ruleB EOF ;
ruleA : something operand anotherthing ;
ruleB : id assign literal ;
operand : ID | LITERAL ;
id : ID ;
literal : LITERAL ;
The parser performs a top-down graph evaluation of the parser rules, starting with the startRule. That is, the parser will evaluate the listed startRule elements in order, sequentially descending through the named sub-rules (and just those sub-rules). Consequently, ruleA will not encounter/consider the id and literal rules.
In this limited example then, there is no conflict in the seemingly overlapping definition of the operand, id, and literal rules.
Update
The OperandContext class will contain ID() and LITERAL() methods returning TerminalNode. The one that does not return null represents the symbol that was actually matched in that specific context. Look at the generated code.

JavaScript parse function JSON.parse does not work as expected

The case:
var s = '{"a": 2}';
var d = JSON.parse(s); // d = Object {a: 2}
It is OK.
The similar case does not parse string, however. Why?
var s = "{'a': 2}";
var d= JSON.parse(s) // Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Expected result - parsed object like in the first case. It should have worked because ' and " are interchangeable in javascript.
According to the standard, you need double quotes to denotes a string, which a key is.
It should have worked because ' and " are interchangeable in javascript.
JSON is not JavaScript.
JSON strings must be delimited with quotation marks, not apostrophes.
See the specification:
A string begins and ends with quotation marks.

convert invalid JSON string to JSON

I have an invalid json string like following,
"{one: 'one', two: 'two'}"
I tried to use JSON.parse to convert it to an object. however, this is not valid json string.
Is there any functions can convert this invalid format into a valid json string or directly convert into an object?
IF your example syntax is the same as your real JSON, JSONLint says you need double quote for the name AND the value.
In this case only, use these replace calls:
var jsontemp = yourjson.replace((/([\w]+)(:)/g), "\"$1\"$2");
var correctjson = jsontemp.replace((/'/g), "\"");
//yourjson = "{one: 'one', two: 'two'}"
//jsontemp = "{"one": 'one', "two": 'two'}"
//correctjson = "{"one": "one", "two": "two"}"
However you should try to work with a valid Json in the first place.
If the question is "can I convert invalid JSON into valid JSON", in the general case the answer is obviously "no"; where would you even start with a string like "$#!~~"?
In this particular case, the JSON is only invalid because the property names are not quoted; as JavaScript, the string is valid and could be parsed using, for example,
var myObj = eval( "x=" + myString );
or better
var myObj = (new Function("return " + myString))();
However, this is potentially very unsafe and you should not do it unless you are positive the string cannot cause harm (which seems unlikely if you aren't in a position to generate valid JSON in the first place). It also won't help you if the JSON code is invalid in other ways, and it will fail if the property names are not valid JS identifiers.
For a proper answer it would be useful to know more about the context of this question.

Parse JSON like string by javascript

I have this variable which is json-like string, error appear while parse to a object
"SyntaxError: JSON.parse: expected ',' or '}' after property value in object"
Code:
var obj = JSON.parse('{"data":[{"from":"{\"category\":\"Bank/financial institution\"}"}],"statusCode":200}');
Seems the function not available for nested "{\"category\":\"Bank/financial institution\"}", replace with simple text (e.g. "123") would be fine, is there any way to handle such cases? Thanks.
The \ (backslash) character before "category is unnecessary.
There's no need to escape a double quote in a single-quoted string.
Your string is indeed malformed.
You either want:
var obj = JSON.parse('{"data":[{"from":{"category":"Bank/financial institution"}}],"statusCode":200}');
...(e.g., without quotes around the value of from and without backslashes) which when deserialized results in an object with a property called data which is an array, which has as its first entry an object with a property called from which is an object: Live Example | Source
or
var obj = JSON.parse('{"data":[{"from":"{\\"category\\":\\"Bank/financial institution\\"}"}],"statusCode":200}');
...(e.g., keeping the quotes around the value for from and making sure the backslashes appear in the JSON, which means escaping them) which is the same until you get to from, which is a string: Live Example | Source
Remove quots for inner object
var obj = {
"data": [{
"from": {
"category": "Bank/financial institution"
}
}],
"statusCode": 200
}

Categories