Check the JSON Response Is Array or Int or String for a Key

check the json response is array or int or string for a key?

There is no need to fall back to Any here. Even problematic JSON like this can be handled with Codable. You just need to keep trying the different types until one works.

struct Thing: Decodable {
let products: [Int]

enum CodingKeys: String, CodingKey {
case products
}

init(from decoder: Decoder) throws {
// First pull out the "products" key
let container = try decoder.container(keyedBy: CodingKeys.self)

do {
// Then try to decode the value as an array
products = try container.decode([Int].self, forKey: .products)
} catch {
// If that didn't work, try to decode it as a single value
products = [try container.decode(Int.self, forKey: .products)]
}
}
}

let singleJSON = Data("""
{ "products": 25 }
""".utf8)

let listJSON = Data("""
{ "products": [77,80,81,86] }
""".utf8)

let decoder = JSONDecoder()

try! decoder.decode(Thing.self, from: singleJSON).products // [25]
try! decoder.decode(Thing.self, from: listJSON).products // [77, 80, 81, 86]

Checking a key is array or string in JSONObject

The mistake in your code is here:

Object notesItrObj=notesIterator.next();

This should be:

Object notesItrObj=notesObj.get(notesKey);

This is because notesIterator.next() returns a key, not a value.

Check if key exists in a json array

You can use a simple null check on the json fields using the ?? operator with a default. Use it like

productName: json["productName"] ?? 'Default Product Name';

That should automatically set the default value Default Product Name if the JSON field is null.

It's essentially a short hand for

productName: json["productName"] != null ? json["productName"] : 'Default Product Name';

How to check whether a JSON key's value is an array or not if you don't know the key

You can try something like this:

Data payload:

const payload =  {
person: [
{
id: 1,
x: 'abc',
attributes: ['something']
},
{
id: 1,
x: 'abc'
}
]
};

Function that will return if some entry has an Array as value:

const arrayEntries = json => {

let response = [{
isArray: false,
jsonKey: null,
jsonValue: null
}];

Object.entries(json).map(entry => {
if (Array.isArray(entry[1])) {
response.push({
isArray: true,
jsonKey: entry[0],
jsonValue: entry[1]
});
}
});

return response;
}

Usage example:

payload.person.map(person => {
console.log(arrayEntries(person));
});

Return will be something like this:

Codepen link: https://codepen.io/WIS-Graphics/pen/ExjVPEz


ES5 Version:

function arrayEntries(json) {

var response = [{
isArray: false,
jsonKey: null,
jsonValue: null
}];

Object.entries(json).map(function(entry) {
if (Array.isArray(entry[1])) {
response.push({
isArray: true,
jsonKey: entry[0],
jsonValue: entry[1]
});
}
});

return response;
}

payload.person.map(function(person) {
console.log(arrayEntries(person));
});

Sample Image

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
}

How to check if a value exists in a JSON Array for a particular key?

First you need to deserialize the JSON code to a JsonArray in this way:

JsonArray jsonArr = gson.fromJson(jsonString, JsonArray.class);

After that you can create this method:

public boolean hasValue(JsonArray json, String key, String value) {
for(int i = 0; i < json.size(); i++) { // iterate through the JsonArray
// first I get the 'i' JsonElement as a JsonObject, then I get the key as a string and I compare it with the value
if(json.get(i).getAsJsonObject().get(key).getAsString().equals(value)) return true;
}
return false;
}

Now you can call the method:

hasValue(jsonArr, "methodName", "addRole");

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 )



Related Topics



Leave a reply



Submit