12

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.

2
  • I think this would depend on your Java code, not Python. Whatever is emitting this JSON is adding "listName" into the structure. Commented Feb 3, 2015 at 17:31
  • note: [{'firstObject' : 'firstVal'}] is not a proper json (json does not use single quotes for strings). How do you observe what is send from java? Commented Feb 3, 2015 at 18:16

2 Answers 2

12

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.

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

Comments

5

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.

Comments

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.