Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a json object is array

Im new to python.I came up with this issue while sending json arraylist obect from java to python.While sending the json object from java the json structure of the arraylist is

[{'firstObject' : 'firstVal'}]

but when i receive it in python i get the value as

{'listName':{'firstObject':'firstVal'}}

when i pass more than one object in the array like this :

[{'firstObject' : 'firstVal'},{'secondObject' : 'secondVal'}]

I am receiving the json from python end as

{'listName':[{'firstObject':'firstVal'},{'secondObject' : 'secondVal'}]}    

I couldnt figure out why this is happening.Can anyone help me either a way to make the first case a array object or a way to figure out whether a json variable is array type.

like image 522
Deepak Ramakrishnan Kalidass Avatar asked Feb 03 '15 17:02

Deepak Ramakrishnan Kalidass


2 Answers

Whenever you use the load (or loads) function from the json module, you get either a dict or a list object. To make sure you get a list instead of a dict containing listName, you could do the following:

import json

jsonfile = open(...) # <- your json file
json_obj = json.load(jsonfile)

if isinstance(json_obj, dict) and 'listName' in json_obj:
    json_obj = json_obj['listName']

That should give you the desired result.

like image 67
Fawers Avatar answered Nov 01 '22 05:11

Fawers


json module in Python does not change the structure:

assert type(json.loads('[{"firstObject": "firstVal"}]')) == list

If you see {'listName':{'firstObject':'firstVal'}} then something (either in java or in python (in your application code)) changes the output/input.

Note: it is easy to unpack 'listName' value as shown in @Fawers' answer but you should not do that. Fix the upstream code that produces wrong values instead.

like image 21
jfs Avatar answered Nov 01 '22 04:11

jfs