1

How to check if a string like this {:[{},{}]}, without any literals, can be represented as a JSON object or not?

The input comes with the following constraints: 1. A JSON object should start with '{' and ends with a '}'. 2. The key and value should be separated by a ':'. 3. A ',' suggests an additional JSON property. 4. An array only consists of JSON objects. It cannot contain a "key":"value" pair by itself.

And it is to be intrepreted like this:

{
"Key": [{
"Key": "Value"
}, {
"Key": "Value"
}]
}
11
  • {} is probably a literal, too :-) Commented Aug 20, 2016 at 6:13
  • Do you mean you want to check if your string is valid JSON (that would parse to an object)? Commented Aug 20, 2016 at 6:13
  • I meant without anything like 'key', 'value, 'abc', '123' etc. Commented Aug 20, 2016 at 6:14
  • 2
    Possible duplicate of How do I check if a string is valid JSON in Python? Commented Aug 20, 2016 at 6:21
  • 1
    What is "the wrong answer"? For the record, it is not valid JSON. See the railroad diagrams here: json.org Commented Aug 20, 2016 at 6:21

1 Answer 1

1

The syntax spec for JSON can be found here.

It indicates that the [{},{}] is legal, because [] has to contain 0 or more elements separated by ,, and {} is a legal element. However, the first part of your example is NOT valid - the : must have a string in front of it. While it is legal for it to be an empty string, it's not legal for it to be null, and the interpretation of a totally missing element is ambiguous.

So. {"":[{},{}]} is legal, but {:[{},{}]} is not.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.