Checking If a String Is Valid JSON Before Trying to Parse It

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;
}

How do I check if a string is valid JSON in Python?

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

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.

How to make sure that string is valid JSON using JSON.NET

Through Code:

Your best bet is to use parse inside a try-catch and catch exception in case of failed parsing. (I am not aware of any TryParse method).

(Using JSON.Net)

Simplest way would be to Parse the string using JToken.Parse, and also to check if the string starts with { or [ and ends with } or ] respectively (added from this answer):

private static bool IsValidJson(string strInput)
{
if (string.IsNullOrWhiteSpace(strInput)) { return false;}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try
{
var obj = JToken.Parse(strInput);
return true;
}
catch (JsonReaderException jex)
{
//Exception in parsing json
Console.WriteLine(jex.Message);
return false;
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
return false;
}
}
else
{
return false;
}
}

The reason to add checks for { or [ etc was based on the fact that JToken.Parse would parse the values such as "1234" or "'a string'" as a valid token. The other option could be to use both JObject.Parse and JArray.Parse in parsing and see if anyone of them succeeds, but I believe checking for {} and [] should be easier. (Thanks @RhinoDevel for pointing it out)

Without JSON.Net

You can utilize .Net framework 4.5 System.Json namespace ,like:

string jsonString = "someString";
try
{
var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
//Invalid json format
Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
Console.WriteLine(ex.ToString());
}

(But, you have to install System.Json through Nuget package manager using command: PM> Install-Package System.Json -Version 4.0.20126.16343 on Package Manager Console) (taken from here)

Non-Code way:

Usually, when there is a small json string and you are trying to find a mistake in the json string, then I personally prefer to use available on-line tools. What I usually do is:

  • Paste JSON string in JSONLint The JSON Validator and see if
    its a valid JSON.
  • Later copy the correct JSON to http://json2csharp.com/ and
    generate a template class for it and then de-serialize it
    using JSON.Net.


Related Topics



Leave a reply



Submit