Introduction

The native function to switch from json is much too limited. It fails if the input text differs slightly from the strict JSON format and the error message is not at all explicit.

JSONEx attempts to remedy this situation by correcting the input text.

JSONEx

Error handling is improved. Instead of indicating a character position in the input string more or less at the parser's misunderstanding, JSONEx indicates the type of expected word, an extract from the input string where it is located. error.

How it works

At first, JSONEx uses the native function of the JSON API. If it fails, the input string is corrected and JSONEx retries the call to the native function a second time. If the parsing fails you get the improved message from the first parsing attempt and the improved message from the 2nd attempt.

Compare

Input JSON Native JSONEx
status message status message undestand
{a:1} error
Unexpected token a in JSON at position 1
ok {"a":1}
{"a":1,} error
Unexpected token } in JSON at position 7
ok {"a":1}
{'a':1} error
Unexpected token ' in JSON at position 1
ok {"a":1}
{"a":[1,2,3,]} error
Unexpected token ] in JSON at position 12
ok {"a":[1,2,3]}
{"a":[1,2,3,'r']} error
Unexpected token ] in JSON at position 12
ok {"a":[1,2,3,"r"]}
{"a:1} error
Unexpected end of JSON input
error
  Unexpected end of JSON input while parsing near 
  {"a:1}
  -----^
  Error: Second chance: parse error at position 6 with state obj_key_str after 
  {"a:1}
  --------------------^
            
[ {"a":1},{"b":2,"bb:3}] error
Unexpected end of JSON input
error
Unexpected end of JSON input while parsing near 
"a":1},{"b":2,"bb:3}]
-----------------------^
Error: Second chance: parse error at position 24 with state obj_key_str after 
[ {"a":1},{"b":2,"bb:3}]
--------------------^

API

JSONEx.parse

JSONEx.parse(text)

textstring to parse

Parse a string as JSON and return the value.

JSONEx.stringify

JSONEx.stringify(obj)

obja object

string

Return a JSON string corresponding to the specified value.

JSONEx.correct

JSONEx.correct(text);

texta json string or similar

try to transform the text to be compatible JSON

JSONEx.replaceNativeJson

JSONEx.replaceNativeJson();

Replace JSON native parser with JSONEx

JSONEx.revertToNativeJson

JSONEx.revertToNativeJson();

Restore JSON native parser