I have a scenario where I am trying to compare list elements with a json file and if there is a match then return certain values and create a json response.
here are my json data
[
{
"evi": 1223,
"evn": "testapp1",
"conf": {
"c_gr": "tot",
"c_id": "112"
}
},
{
"evi": 6759,
"evn": "testapp2",
"conf": {
"c_gr": "tot",
"c_id": "112"
}
},
{
"evi": 3352,
"evn": "testapp3",
"conf": {
"c_gr": "tot7",
"c_id": "112"
}
}
]
Here is what I have tried so far :
response=requests.post('https://testaapp.com', headers=headers, data=data)
resp_json=response.json()
if response.status_code == 200:
print ('working fine...!!')
else:
print ('notworking !!')
metadata=resp_json['data']
m_list=[1123, 123445, 61887, 3352, 35811488976]
final_lst_data1 = []
final_lst_data2 = []
for key in m_list:
temp1= key
for keya in metadata:
if temp1 in metadata[keya]['evi']:
final_lst_data1.append(metadata['evn']) #return the names
final_lst_data2.append(metadata['evn'], metadata['conf']) #return evn and conf values after checking and then dump it to json from list in same json format if not possible then convert to json from list, not sure how to do this here.
But this doesnt works as it gives me below error
if key in metadata[keya]['evi']:
TypeError: list indices must be integers or slices, not dict
You are using a dictionary as an index. When you say "for keya in metadata:", keya is a dictionary that refers to the list of dictionaries inside 'metadata'. So, you don't need to use metadata[keya] to access each element, you can just use 'keya'.
for keya in metadata:
if temp1 == keya['evi']:
final_lst_data1.append(keya['evn'])
final_lst_data2.append([keya['evn'], keya['conf']])
Related
on a nested JSON object, I would like to modify values and adding a JSON Object.
Assume a JSON Object like this:
{
"key1": "value1",
"key2": {
"key2_1": "value2_2 ",
"key2_2": {
"key2_2_1 ": "value2_2_1"
},
"key2_3": "value2_3",
"key2_4": {
"key2_4_1": [{
"key2_4_1_1a": "value2_4_1_1a",
"key2_4_1_2a": "value2_4_1_2a"
}, {
"key2_4_1_1b": "value2_4_1_1b",
"key2_4_1_2b": "value2_4_1_2b"
}]
}
},
"key3": {
"key3_1": "value3_2 ",
"key3_2": {
"key3_2_1 ": "value3_2_1"
},
"key3_3": "value3_3",
"key3_4": {
"key3_4_1": {
"key3_4_1_1": "value3_4_1_1"
}
}
}
}
now the JSON will be recursive iterated to search for a specific value.
The replacement value can be a string
repl = 'MyString'
a dict string
repl = '''{"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}'''
or a list
repl = '''[{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]'''
so after I found the key where the replacement to add, I would like to replace the existing value for the given key.
eg for the string:
a[key] = repl
How I can do this for dict or list replacements?
The result could be depending on the replacement variable, the string eg in "key2_1", the dict in "key2_2_1" or the list in "key2_3". The keys where string,dict or list are inserted are examples.
{
"key1": "value1",
"key2": {
"key2_1": "MyString",
"key2_2": {
"key2_2_1 ": {"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}
},
"key2_3": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}],
"key2_4": {
"key2_4_1": [{
"key2_4_1_1a": "value2_4_1_1a",
"key2_4_1_2a": "value2_4_1_2a"
}, {
"key2_4_1_1b": "value2_4_1_1b",
"key2_4_1_2b": "value2_4_1_2b"
}]
}
}
}
i have a search function:
def searchNreplace(data, search_val, replace_val):
if isinstance(data, list):
return [searchNreplace(listd, search_val, replace_val) for listd in data]
if isinstance(data, dict):
return {dictkey: searchNreplace(dictvalue, search_val, replace_val) for dictkey, dictvalue in data.items()}
return replace_val if data == search_val else data
print(searchNreplace(data, "key3", repl))
If you really don't struggle with finding a key, you can use json library to parse your string to object and just assign it as str.
import json
repl = """{"MyKey": [{"MyKey1": "MyValye1"},{"MyKey2": "MyValye2"}]}"""
a[key] = json.loads(repl)
After that you can dump content back to file
with open("my_file", "w+") as f:
json.dump(a, f)
so i would like to list the first value of users json i get from making an rest api call with python so that the response is like this :
0 :"XXX-XXX", 1 :"DDD-DDD", 2: "KKK-KKK", 3 :"UUU-UUU"
Json Data from API call:
"XXX-XXX":{
"Info":{
"ID":"08",
"Created": "2021-07-10",
"Plan": "Basic"}},
"DDD-DDD":{
"Info":{
"ID":"04",
"Created": "2021-07-11",
"Plan": "Prime"}}
},
"KKK-KKK":{
"Info":{
"ID":"02",
"Created": "2021-07-11",
"Plan": "Prime"}}
},
"UUU-UUU":{
"Info":{
"ID":"13",
"Created": "2021-07-11",
"Plan": "Prime"}}
}
}```
OK, so the solution is simple. Python includes a JSON module. So first you load the JSON as a Python dictionary using the load() method, then call the keys() method on the dictionary to get an iterable containing the keys. An iterable means you can iterate over it as if it were a list, but if you absolutely need a list, you can convert that object to a list.
Here's some code:
import json
json_string = """ { "X": {"name":"hi"},"Y": {name:"yo"}}
"""
dictionary = json.loads(json_string) # get a dictionary from the JSON
keys = dictionary.keys() # get the keys of the dictionary
for key in keys: #iterate over keys
print(key)
key_list = list(keys) # converts keys to a Python list
How can I iterate over this to get get MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, and all the value in the 'item' list for instance value for PhoneNumber.
Am getting this data from a callBackURl after a user makes a payment.
"Body":{
"stkCallback":{
"MerchantRequestID":"19465-780693-1",
"CheckoutRequestID":"ws_CO_27072017154747416",
"ResultCode":0,
"ResultDesc":"The service request is processed successfully.",
"CallbackMetadata":{
"Item":[
{
"Name":"Amount",
"Value":1
},
{
"Name":"MpesaReceiptNumber",
"Value":"LGR7OWQX0R"
},
{
"Name":"Balance"
},
{
"Name":"TransactionDate",
"Value":20170727154800
},
{
"Name":"PhoneNumber",
"Value":254721566839
}
]
}
}
}
}```
I want to get MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, and all the value in the list
'item' then store them in the db.
```new_user = MpesaResponses(MerchantRequestID=data[0]['Body']['stkCallback']['MerchantRequestID'],
CheckoutRequestID=data[0]['Body']['stkCallback']['CheckoutRequestID'],
ResultCode=data[0]['Body']['stkCallback']['ResultCode'],
ResultDesc=data[0]['Body']['stkCallback']['ResultDesc'],
Amount=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][0]
['value'],
MpesaReceiptNumber=data[0]['Body']['stkCallback']['CallbackMetadata']
['Item'][1]['value'],
TransactionDate=data[0]['Body']['stkCallback']['CallbackMetadata']['Item']
[3]['value'],
PhoneNumber=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][4]
['value'])
db.session.add(new_user)
db.session.commit()```
This is what I had tried.
If the data is just a dictionary starting at "Body" and not a list containing a dictionary, then just remove the first [0] from each variable, then check your spelling on Value as so:
MerchantRequestID=data['Body']['stkCallback']['MerchantRequestID']
CheckoutRequestID=data['Body']['stkCallback']['CheckoutRequestID']
ResultCode=data['Body']['stkCallback']['ResultCode']
ResultDesc=data['Body']['stkCallback']['ResultDesc']
Amount=data['Body']['stkCallback']['CallbackMetadata']['Item'][0]['Value']
MpesaReceiptNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value']
TransactionDate=data['Body']['stkCallback']['CallbackMetadata']['Item'][3]['Value']
PhoneNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value']
I have this sample json data that is coming as a response from a POST request- response is the name of below sample json data variable:
{
"statusCode": "OK",
"data": [
{
"id": -199,
"result": {
"title": "test1",
"group": "test_grp2"
}
},
{
"id": -201,
"result": {
"title": "test2",
"group": "test_grp2"
}
}
]
}
Now what I want to do is form a list of list where each list will have id,title,and group values from above json data. Here is what my code looks like:
def get_list():
# code to get the response from POST request
json_data = json.loads(response.text)
group_list = []
if json_data['statusCode'] == 'OK':
for data in json_data['data']:
print(data)
for result_data in data['result']:
title = result_data['title']
group = result_data['group']
group_list.append([data['id'],title,group])
return(group_list)
When I execute this I get error as list indices must be int not str at line title = result_data['title]. How can I form the list of list above?
data['result'] in your case is a dictionary. When you iterate over it using for result_data in data['result'], you get the keys - in other words, result_data is a string and it does not support string indexing.
Instead, you meant:
for data in json_data['data']:
result_data = data['result']
title = result_data['title']
group = result_data['group']
Or, alternatively, you can make use of a list comprehension:
group_list = [(data['id'], data['result']['title'], data['result']['group'])
for data in json_data['data']]
print(group_list)
You can extract the list of lists directly using a list comprehension:
>>> [[d['id'], d['result']['title'], d['result']['group']] for d in json_data['data']]
[[-199, 'test1', 'test_grp2'], [-201, 'test2', 'test_grp2']]
I want to display JSON in specific format and data will be from database.So how to form in specific format in python.Format of JSON is
{
"data":{"Device Id" : value from db,"Date":Current Time},
"Data":
{
"Temperature":
{
value from db
},
"Consumptions":
{
value from db
},
"Error":
[
{
value from db
}
]
}
}
I have tried this:
dict((query.description[i][0], value) for i, value in enumerate(row)) for row in query.fetchall()
But I'm not getting desired output and i'm unable to pass data to json. So how to pass data to json.
Error Im getting is Dictionay update sequence element 0# has length 1; 2 is required
Did you use json module?
import json
print json.dumps(yourStructure, indent=6)