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.
Related
I have created an example with a nested dict of list of tuples here:
Build dict from list of tuples combining two multi index dfs and column index
However, when I call
with open('output/test.json', "w") as f:
json.dump(solution, f, ensure_ascii=False)
I get the error message "TypeError: 0 is not JSON serializable". However, number 0 does not show up as a key, only as value in a tuple in a list. Thus it should not be a string problem? So, where is the problem, and how can I solve it?
I was suddenly wondering, why my real data json dump worked out, but not the example in the link. The solution is, that the example enforced integer values, which are apparently not serializable. So, I changed the numbers also to float in my example. Now it works fine with json dump. Thanks for your hints.
I have written this code:
myarray = []
myarray.append('abc')
myarray.append('def')
return json.dumps(myarray)
This is part of a GraphQL function. What I get back is the equivalent of this:
"myArray": "[\"abc\", \"def\"]"
How can I eliminate the backslashes?
Robert
You haven't shown enough code to reproduce this error. Presumably, whatever is calling this function is also converting to json. So you should return myarray directly, without converting to json in this function.
My predicament turned out to be that GraphQL (via Graphene-Django) was already turning the array into JSON. Thus I was effectively converting to JSON twice. I solved the problem by just returning myarray directly.
I have a piece of code that allows me to print dictionary items returned using .json() method on an XHR response from a website:
teamStatDicts = responser[u'teamTableStats']
for statDict in teamStatDicts:
print("{seasonId},{tournamentRegionId},{minsPlayed},"
.decode('cp1252').format(**statDict))
This prints in the following format:
9155,5,900
9155,5,820
...
...
...
9155,5,900
9155,5,820
The above method works fine, providing the keys in the dictionary never change. However in some of the XHR submissions I am making they do. Is there a way that I can print all dictionary values in exactly the same format as above? I've tried a few things but really didn't get anywhere.
In general, give a dict, you can do:
print(','.join(str(v) for v in dct.values()))
The problem here is you don't know the order of the values. i.e. is the first value in the CSV data the seasonId? Is the the tournamentRegionId? the minsPlayed? Or is it something else entirely that you don't know about?
So, my point is that unless you know the field names, you can't put them in a string in any reliable order if the data comes to you as vanilla dicts.
If you're decoding the XHR elsewhere using json, you could make the object_pairs_hook an OrderedDict:
from collections import OrderedDict
import json
...
data = json.loads(datastring, object_pairs_hook=OrderedDict)
Now the data is guaranteed to be in the same order as the datastring was, but that only helps if the data in datastring was ordered in a particular way (which is usually not the case).
I am in trouble with the bing's json api.
Here is the json data i am receiving from api.bing.net/json.aspx:
{"SearchResponse":{"Version":"2.2","Query":{"SearchTerms":"news"},"Translation":{"Results":[{"TranslatedTerm":"Noticias"}]}}}
I need to parse the TranslatedTerm value "Noticias" but it seems i have a problem with the json decode. I am using this..
result = j.loads(bytes)
print result['SearchResponse']['Translation']['Results']
And python gives me this:
[{u'TranslatedTerm': u'Noticias'}]
If i add use it like this:
result['SearchResponse']['Translation']['Results']["TranslatedTerm"]
python raises an error like
print result['SearchResponse']['Translation']['Results']["TranslatedTerm"]
TypeError: list indices must be integers
How can i get the 'Noticias' as a plain string? Much appriciated...
The translation Results is a list - presumably because there can be many results.
If you're sure you're only interested in the first result, you can do this:
result['SearchResponse']['Translation']['Results'][0]['TranslatedTerm']
Is it possible to convert a json string (for e.g. the one returned from the twitter search json service) to simple string objects. Here is a small representation of data returned from the json service:
{
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}
Lets say that I somehow store the result in some variable, say, obj. I am looking to get appropriate values like as follows:
print obj.max_id
print obj.since_id
I've tried using simplejson.load() and json.load() but it gave me an error saying 'str' object has no attribute 'read'
I've tried using simplejson.load() and json.load() but it gave me an error saying 'str' object has no attribute 'read'
To load from a string, use json.loads() (note the 's').
More efficiently, skip the step of reading the response into a string, and just pass the response to json.load().
if you don't know if the data will be a file or a string.... use
import StringIO as io
youMagicData={
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}
magicJsonData=json.loads(io.StringIO(str(youMagicData)))#this is where you need to fix
print magicJsonData
#viewing fron the center out...
#youMagicData{}>str()>fileObject>json.loads
#json.loads(io.StringIO(str(youMagicData))) works really fast in my program and it would work here so stop wasting both our reputation here and stop down voting because you have to read this twice
from https://docs.python.org/3/library/io.html#text-i-o
json.loads from the python built-in libraries, json.loads requires a file object and does not check what it's passed so it still calls the read function on what you passed because the file object only gives up data when you call read(). So because the built-in string class does not have the read function we need a wrapper. So the StringIO.StringIO function in short, subclasses the string class and the file class and meshing the inner workings hears my low detail rebuild https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1
so at the end of all that its like writing a ram file and jsoning it out in one line....