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.
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.
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.
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