By ""invalid" JSON" I mean these (or a part thereof):
(Example partly taken from json5.org)
{
// Single line comment
# This too
/*
Block
comments
*/
unquoted: 'and you can quote me on that',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Look, Mom! \
No \\n's!",
tripleQuotes: '''
for the win!
''',
hexadecimal: 0xdec13a7,
leadingDecimalPoint: .8675309, andTrailing: 8675309.,
positiveSign: +1,
infinity: -Infinity, and: NaN,
trailing: {comma: 'in objects',}, andIn: ['arrays',],
orSomethingCrazier: like these
// => "like these"
noEscapeNeeded: \w+
// => "\\w+"
multipleCommas: ["first",,,, "second", {"third": 3,,,, secondKeyOfThird: 4}]
noCommaBetweenEntries: [and 'unquoted-strings'] // => ["and", "unquoted-strings"]
}
There are a lot of questions asking for a way to "fix" text like this with regex. An user at a recent PHP question found 5 of them (all about PHP):
- Invalid JSON parsing using PHP
- php json_decode fails without quotes on key
- How to json_decode invalid JSON with apostrophe instead of quotation mark
- Handling malformed JSON in PHP
- Convert invalid json into valid json
Some other questions I found by googling:
- How to fix invalid JSON with RegExp in Javascript? javascript
- Parse JSON with no quotes in JavaScript javascript
- How to parse JSON string containing "NaN" in Node.js javascript
- Parsing json, key without quotes objective-c
- How to Fix JSON Key Values without double-quotes? python
- Bad JSON - Keys are not quoted python
- Parsing JSON without quoted keys ruby
The list goes on and on.
Most of the answers I read are regex-based; others suggest using superclasses of JSON which support some of the above syntax (I have yet to find a language that works with all of them; not even JS itself): YAML, JSON5, Relaxed JSON, HJSON, etc.
I think a canonical question is needed where readers can find language-oriented answers on how to use implementations of these data formats. Has there already been one? If there is no such question, should we create one?
//
and/**/
comments, single-quoted strings, hexadecimal(/binary?) numbers and trailing commas. Would a question consisting of those alone can somewhat suffice as a valid one?{"some_key": "a", "some_key": "b", "some_key": "c"}
- The most common result was that only the last key prevailed and the rest was silently dropped. The correct, of course, would be to throw an error and reject the input instead.