Reputation: 407
I've JSON there I want to identify whether it is an array of an object or just an array of string. How can we identify this in python?
arrayA = [{"name", "john", "address": "usa"}, {"name":"adam": "china"}]
arrayB = ["Country", "State"]
Upvotes: 1
Views: 197
Reputation: 3745
The list comprehension will iterate over the list and create a new list with a boolean for each value. The value of the boolean depend of the type of the element.
Then, all()
will check if all the elements in the sequence is True
.
array_a = [{"name": "john", "address": "usa"},
{"name": "adam", "address": "china"}]
array_b = ["Country", "State"]
array_c = ["Country", "State", {"name": "adam", "address": "china"}]
print(all(isinstance(elem, str) for elem in array_a))
# False
print(all(isinstance(elem, str) for elem in array_b))
# True
print(all(isinstance(elem, str) for elem in array_c))
# False
If you don't know this form of statement [<expression> for <variable> in <iterable>]
, this is how it works: Data Structures - List Comprehensions
edit: Thanks B. Morris for your comment ;)
Upvotes: 1