How to check whether the given object is object or Array in JSON string
JSON objects and arrays are instances of JSONObject
and JSONArray
, respectively. Add to that the fact that JSONObject
has a get
method that will return you an object you can check the type of yourself without worrying about ClassCastExceptions, and there ya go.
if (!json.isNull("URL"))
{
// Note, not `getJSONArray` or any of that.
// This will give us whatever's at "URL", regardless of its type.
Object item = json.get("URL");
// `instanceof` tells us whether the object can be cast to a specific type
if (item instanceof JSONArray)
{
// it's an array
JSONArray urlArray = (JSONArray) item;
// do all kinds of JSONArray'ish things with urlArray
}
else
{
// if you know it's either an array or an object, then it's an object
JSONObject urlObject = (JSONObject) item;
// do objecty stuff with urlObject
}
}
else
{
// URL is null/undefined
// oh noes
}
Determine whether JSON is a JSONObject or JSONArray
I found better way to determine:
String data = "{ ... }";
Object json = new JSONTokener(data).nextValue();
if (json instanceof JSONObject)
//you have an object
else if (json instanceof JSONArray)
//you have an array
tokenizer is able to return more types: http://developer.android.com/reference/org/json/JSONTokener.html#nextValue()
How to check if it is a JsonArray or JsonObject in Javascript
You can use Array.isArray
to check if it is array:
if (Array.isArray(json['amazon'])) {
// It is array
}
and you can check if type of object is object
to determine if it is an object. Please refer, for example, this answer for the reason why check for null is separate:
if (json['flipkart'] !== null && typeof (json['flipkart']) === 'object') {
// It is object
}
Determine if Json results is object or array
Using Json.NET, you could do this:
string content = File.ReadAllText(path);
var token = JToken.Parse(content);
if (token is JArray)
{
IEnumerable<Phone> phones = token.ToObject<List<Phone>>();
}
else if (token is JObject)
{
Phone phone = token.ToObject<Phone>();
}
How to check if the JSON Object array contains the value defined in an arrary or not?
Try the following:
var categories = [ {catValue:1, catName: 'Arts, crafts, and collectibles'}, {catValue:2, catName: 'Baby'}, {catValue:3, catName: 'Beauty and fragrances'}, {catValue:4, catName: 'Books and magazines'}, {catValue:5, catName: 'Business to business'}, {catValue:6, catName: 'Clothing, accessories, and shoes'}, {catValue:7, catName: 'Antiques'}, {catValue:8, catName: 'Art and craft supplies'}, {catValue:9, catName: 'Art dealers and galleries'}, {catValue:10, catName: 'Camera and photographic supplies'}, {catValue:11, catName: 'Digital art'}, {catValue:12, catName: 'Memorabilia'}];
var categoriesJson = JSON.stringify(categories);var mainCat = ['Arts, crafts, and collectibles', 'Baby' , 'Antiques']
$.each(JSON.parse(categoriesJson) , function (key, value) { if(mainCat.indexOf(value.catName) > -1){ console.log('Exists: ' +value.catName) } else{ console.log('Does not exists: ' +value.catName) }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Test if it is JSONObject or JSONArray
Something like this should do it:
JSONObject json;
Object intervention;
JSONArray interventionJsonArray;
JSONObject interventionObject;
json = RestManager.getJSONfromURL(myuri); // retrieve the entire json stream
Object intervention = json.get("intervention");
if (intervention instanceof JSONArray) {
// It's an array
interventionJsonArray = (JSONArray)intervention;
}
else if (intervention instanceof JSONObject) {
// It's an object
interventionObject = (JSONObject)intervention;
}
else {
// It's something else, like a string or number
}
This has the advantage of getting the property value from the main JSONObject
just once. Since getting the property value involves walking a hash tree or similar, that's useful for performance (for what it's worth).
How to tell if return is JSONObject or JSONArray with JSON-simple (Java)?
Simple Java:
Object obj = new JSONParser().parse(result);
if (obj instanceof JSONObject) {
JSONObject jo = (JSONObject) obj;
} else {
JSONArray ja = (JSONArray) obj;
}
You could also test if the (purported) JSON starts with a [
or a {
if you wanted to avoid the overhead of parsing the wrong kind of JSON. But be careful with leading whitespace.
Check if JSON is Object or Array
How to check if JavaScript object is JSON
I'd check the constructor attribute.
e.g.
var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;
function whatIsIt(object) {
if (object === null) {
return "null";
}
if (object === undefined) {
return "undefined";
}
if (object.constructor === stringConstructor) {
return "String";
}
if (object.constructor === arrayConstructor) {
return "Array";
}
if (object.constructor === objectConstructor) {
return "Object";
}
{
return "don't know";
}
}
var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];
for (var i=0, len = testSubjects.length; i < len; i++) {
alert(whatIsIt(testSubjects[i]));
}
Edit: Added a null check and an undefined check.
Check whether a value exists in JSON object
var JSON = [{"name":"cat"}, {"name":"dog"}];
The JSON variable refers to an array of object with one property called "name".
I don't know of the best way but this is what I do?
var hasMatch =false;
for (var index = 0; index < JSON.length; ++index) {
var animal = JSON[index];
if(animal.Name == "dog"){
hasMatch = true;
break;
}
}
Related Topics
How to Bypass Google Recaptcha for Testing Using Selenium
How to Mock a Rest Template Exchange
How to Process a Multipart Request Consisting of a File and a Json Object in Spring Restful Service
How to Parse Json Boolean Value
Jackson @Jsonproperty Not Working If Property Name Not Equal Field Name
How to View Apache Parquet File in Windows
How to Open a .Dat File in Java Program
How to Multiply a and B With My Recursive Method
How to Fix: Error Creating Bean With Name:Unsatisfied Dependency Expressed Through Field
Forwarding the Request from One Jsp to Another Jsp With All Request Parameters
Dynamically Change Application.Properties Values in Spring Boot
How Many Times Will This Loop Execute
How to Get the First Date and Last Date of the Previous Month (Java)
Returning Json Object as Response in Spring Boot
Spring Boot JPA Unknown Column in Field List
How to Query Multiple Hash Keys in Dynamodb