I have a JSON string
String str = '{ "name":"John", "age":31, "city":"New York" }'
In the above string, city is an optional key and may not be present in the JSON data.
I decoded the json string
var jsonResponse = json.decode(str);
I want to get to know the existence of city key the jsonResponse object.
There are mainly two methods to check the existence of a key in JavaScript Object. The first one is using “in operator” and the second one is using “hasOwnProperty() method”. Method 1: Using 'in' operator: The in operator returns a boolean value if the specified property is in the object.
The two primary parts that make up JSON are keys and values. Together they make a key/value pair. Key: A key is always a string enclosed in quotation marks. Value: A value can be a string, number, boolean expression, array, or object.
To check null in JavaScript, use triple equals operator(===) or Object is() method. If you want to use Object.is() method then you two arguments. 1) Pass your variable value with a null value. 2) The null value itself.
jsonResponse.containsKey("key");
I am not sure how good is the solution, but it is working.
String str = '{ "name":"John", "age":31, "city":"New York" }';
Map<String, String> jsonResponse = json.decode(str);
if (jsonResponse.containsKey('city')){
// do your work
}
Instead of capturing the JSON object in var, capture it into a
Map<String, String>
or
Map<String, Object> //if value is again an object
The result of json.decode
is a Map<String, dynamic>
with an entry for each key/value pair in the source.
As a Map
, you can test for the presence of a key using Map.containsKey. You can also just do a lookup using the "city"
key and see if you get null
back. In some cases it's more convenient to just use the null
value directly than to do an extra check on whether there is something, but that depends entirely on what you are trying to do.
var map = jsonDecode(str);
bool containsCity = map.containsKey("city");
String city = map["city"];
if (city == null) // no city ...
// Use the null directly if you just replace it with a default.
print("${map["name"]} from ${map["city"] ?? "somewhere"}");
// Use a test if you want to do something different if it's there.
print(map["name"] + (city != null ? " from $city" : "");
The map["city"] == null
test differs from map.containsKey("city")
in the case where your original source contained the pair "city": null
. You need to decide whether that ever happens, and if it does, how you want to treat it. In many cases, it's probably an error, and should be treated as if there was no "city"
entry, so I'll usually prefer to use the map["city"] == null
test over map.containsKey("city")
.
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