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']
Related
I am using below code for Json load which works fine for valid json string, but for non valid it throws error.
orgdf['data'].apply(json.loads)
I just need to know for which index (row number) there is an invalid record for which Jason.loads giving error.
I know I can do it using dataframe enumeration (for loop), but looking for an efficient way to do that as it contains Million records.
It will be great if someone can help on the same.
You can create a custom function where you wrap the json.loads call in a try/except and then call this function inside apply. See also this answer.
def is_valid_json(s):
try:
json.loads(s)
except (json.JSONDecodeError, ValueError):
return False
return True
# Mark valid JSON strings
valid = orgdf['data'].apply(is_valid_json)
# Extract indices with _invalid_ strings
invalid_indices = valid[~valid].index
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'm hoping to get your help on decoding a response I'm getting from an API into Python 3, and break it down into variables. It's almost a list, see for yourself:
API returns this:
['b', "[[1465617600000,591.41,651.95,587.96,647.45,1474960.0,240144.89982940466],[1465704000000,647.2,700.68,644.09,698.55,1605710.0,242030.50812923996]]'"]
I'll assign that to lets say.. variable apiReturn. I'm trying to break all the numbers down into individual variables, specifically with the formatting.
I'd like to do something like:
print(apiReturn[0][0])
and get:
1465185600000
Just playing around with trying to print that data here, to no avail:
print(apiReturn.split("'"))
print(apiReturn.split("'"[0][0]))
print(apiReturn.split("[", 1 )[1][0])
Use ast.literal_eval:
import ast
api_return = apiReturn[1][:-1] # [:-1]: is there an extra quote trailing the second item?
# '[[1465185600000,589.02,600.0,585.01,591.78,401760.0,67821.2330781393],[1465272000000,592.31,595.45,570.32,581.12,396206.0,67722.36141861044]]'
api_val = ast.literal_eval(api_return)
print(api_val[0][0])
# 1465185600000
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.