To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.
Usage: isJSON({}) will be false , isJSON('{}') will be true . To check if something is an Array or Object (parsed JSON): // vanillaJS function isAO(val) { return val instanceof Array || val instanceof Object ?
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:
Use JContainer.Parse(str)
method to check if the str is a valid Json. If this throws exception then it is not a valid Json.
JObject.Parse
- Can be used to check if the string is a valid Json objectJArray.Parse
- Can be used to check if the string is a valid Json ArrayJContainer.Parse
- Can be used to check for both Json object & Array
Building on Habib's answer, you could write an extension method:
public static bool ValidateJSON(this string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
Which can then be used like this:
if(stringObject.ValidateJSON())
{
// Valid JSON!
}
Just to add something to @Habib's answer, you can also check if given JSON is from a valid type:
public static bool IsValidJson<T>(this 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 = JsonConvert.DeserializeObject<T>(strInput);
return true;
}
catch // not valid
{
return false;
}
}
else
{
return false;
}
}
I found that JToken.Parse incorrectly parses invalid JSON such as the following:
{
"Id" : ,
"Status" : 2
}
Paste the JSON string into http://jsonlint.com/ - it is invalid.
So I use:
public static bool IsValidJson(this string input)
{
input = input.Trim();
if ((input.StartsWith("{") && input.EndsWith("}")) || //For object
(input.StartsWith("[") && input.EndsWith("]"))) //For array
{
try
{
//parse the input into a JObject
var jObject = JObject.Parse(input);
foreach(var jo in jObject)
{
string name = jo.Key;
JToken value = jo.Value;
//if the element has a missing value, it will be Undefined - this is invalid
if (value.Type == JTokenType.Undefined)
{
return false;
}
}
}
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;
}
return true;
}
⚠️ Alternate option using System.Text.Json
⚠️
For .Net Core one can also use the System.Text.Json
namespace and parse using the JsonDocument
. Example is an extension method based on the namespace operations:
public static bool IsJsonValid(this string txt)
{
try { return JsonDocument.Parse(txt) != null; } catch {}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With