1

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"]
9
  • Do you know how to check the type of a value? How to access an element from a list? Commented Nov 26, 2020 at 18:06
  • Yes. like using isinstance (report_object_in_json, list) ? Commented Nov 26, 2020 at 18:11
  • So have you tried that? What happened? Note that when you parse JSON in Python arrays become lists and objects become dictionaries. Commented Nov 26, 2020 at 18:12
  • Yeah, I did and it passed. Passed for both arrayA and arrayB Commented Nov 26, 2020 at 18:14
  • Then what is your problem? Commented Nov 26, 2020 at 18:17

1 Answer 1

1

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 ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Haha mybad that's true !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.