Is This Simple String Considered Valid JSON

Is this simple string considered valid JSON?

Yes, in most contexts. It is valid JSON syntax representing a JSON value.

The confusion around this comes from Douglas Crockford's RFC 4627, which originally defined the application/json internet media type in 2006. It said that:

A JSON text is a serialized object or array.

However, as Crockford explained in a post in 2013 (unfortunately deleted with rest of Google+, but archived here):

JSON is just a grammar, and the grammar includes numbers and strings. Uses of JSON must necessarily be more restrictive. RFC-4627 is one possible use, and was never intended to be the standard for JSON itself.

The example string is a valid JSON value, but it would have been incorrect to use it as the full "JSON text" body of an application/json HTTP response. However, that's no longer true: RFC-4627 was obsoleted in 2014 with the publication of RFC 7159, which lets you use any JSON value:

A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array.

A "standard for JSON itself" was also published in 2013, as ECMA-404, and JSON was also defined in edition 5.1 of the ECMAScript (JavaScript) specification ECMA-262. These specifications and most parsers allow any JSON value as a complete JSON text, even if it's just a simple string.

Is a plain string valid JSON?

Important


This answer once said No, the first character of the JSON must be a { or a [.

At the time I wrote that, I was testing it with Python. In Python (2.7.x at least), json.loads("a") gives an error, which means that a plain string is not valid JSON there.

It has been rightfully pointed out by others that it cannot be said that a plain string is not valid JSON. See this question for a more appropriate answer.

At this time all I can say is that it depends on your environment. In javascript it may be valid, in python it may not be, etc, etc.

JSON stands for JavaScript Object Notation

Here is a quote from the official site

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array. An ordered list of values. In most
languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming
languages support them in one form or another. It makes sense that a
data format that is interchangeable with programming languages also be
based on these structures.

In JSON, they take on these forms:

An object is an unordered set of name/value pairs. An object begins
with { (left brace) and ends with } (right brace). Each name is
followed by : (colon) and the name/value pairs are separated by ,
(comma).

Take note of the text I bolded.

Because of that, and JSON being JS Object Notation, it is implied that a JSON representation of a name:value pair must always be in the form of

{
"name": "value"
}

Note that you can also make the 'root object' a list

[
{
"name1": "value1"
},
{
"name2": "value2"
}
]

This basically means that the JSON contains more than one object.


As Sunny R Gupta pointed out, this is also valid JSON

[
"this",
"is",
"valid"
]

Note that this works because the strings are not in the form "name":"value" but just strings. Taking that into consideration valid options for your example would be

{
"name": "Morpheus"
}

or

[
"morpheus"
]

The first character of the JSON must be a { or a [

How to check if a string is a valid JSON string?

A comment first. The question was about not using try/catch.

If you do not mind to use it, read the answer below.
Here we just check a JSON string using a regexp, and it will work in most cases, not all cases.

Have a look around the line 450 in https://github.com/douglascrockford/JSON-js/blob/master/json2.js

There is a regexp that check for a valid JSON, something like:

if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

//the json is ok

}else{

//the json is not ok

}

EDIT: The new version of json2.js makes a more advanced parsing than above, but still based on a regexp replace ( from the comment of @Mrchief )

How to test if a string is JSON or not?

Use JSON.parse

function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}

What is the minimum valid JSON?

At the time of writing, JSON was solely described in RFC4627. It describes (at the start of "2") a JSON text as being a serialized object or array.

This means that only {} and [] are valid, complete JSON strings in parsers and stringifiers which adhere to that standard.

However, the introduction of ECMA-404 changes that, and the updated advice can be read here. I've also written a blog post on the issue.


To confuse the matter further however, the JSON object (e.g. JSON.parse() and JSON.stringify()) available in web browsers is standardised in ES5, and that clearly defines the acceptable JSON texts like so:

The JSON interchange format used in this specification is exactly that described by RFC 4627 with two exceptions:

  • The top level JSONText production of the ECMAScript JSON grammar may consist of any JSONValue rather than being restricted to being a JSONObject or a JSONArray as specified by RFC 4627.

  • snipped

This would mean that all JSON values (including strings, nulls and numbers) are accepted by the JSON object, even though the JSON object technically adheres to RFC 4627.

Note that you could therefore stringify a number in a conformant browser via JSON.stringify(5), which would be rejected by another parser that adheres to RFC4627, but which doesn't have the specific exception listed above. Ruby, for example, would seem to be one such example which only accepts objects and arrays as the root. PHP, on the other hand, specifically adds the exception that "it will also encode and decode scalar types and NULL".

Is '' a valid JSON string?

So, I don't think "" should be a valid JSON string

It is a valid JSON string (which is a data type that may appear in a JSON text).

as its neither a list values(i.e. does not start with '[' and ends with ']')

A JSON text (i.e. a complete JSON document) must (at the outermost level) be either an object or an array. A string is not a valid JSON text.

The formal specification says:

A JSON text is a serialized object or array.

But back to quoting the question here:

but JSON.parse doesn't give exception and returns empty string.

The JSON parser you are using is being overly-liberal. Don't assume that all JSON parsers will be.

For example, if I run perl -MJSON -E'say decode_json(q{""})' I get:

JSON text must be an object or array (but found number, string, true, false or null, use allow_nonref to allow this) at -e line 1.

How to check whether a given string is valid JSON in Java

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.

Check whether the String is a Valid JSON String or not?

If you need to be sure it really is valid JSON you're going to need to parse it. A fast, simple, lightweight parser that I like is json-simple. Have a look at their examples here.

http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_2_-_Faster_way:_Reuse_instance_of_JSONParser

Adapting your code I get:

JSONParser parser = new JSONParser();
ResultSet rs = preparedStatement.executeQuery();

while (rs.next()) {
for (String column : columnsList.split(",")) {
//check whether rs.getString(column) is a valid JSON String?
try{
parser.parse(rs.getString(column));
System.out.println("Valid JSON String data");
} catch (ParseException e) {
System.out.printlnn("Invalid JSON String data");
}
}
}


Related Topics



Leave a reply



Submit