'Is there a way in python write json on redis record by record
I have the following json file content :
{
"transactions":
"tr1": {
"type":"deposit",
"account_id":123456789012345,
"amount":20000.0
},
"tr2": {
"type":"deposit",
"account_id":555456789012345,
"amount":20000.0
},
"tr3":{
"type":"payment",
"account_id":123456789012345,
"amount":20000.0
},
"tr4":{
"type":"transfer",
"from":555456789012345,
"to":123456789012345,
"amount":20000.0
}
}
I need to write the information of each transaction on Redis using python program! is there a way to do this ?
I have tryied this , but it insert everything under one key 'traninfo'
data=json.load(f)
for i in data['transactions']:
r.execute_command('JSON.SET','traninfo','.', json.dumps(data))
Solution 1:[1]
The matter with the snippet you give is that at each loop you put the whole json as value of your key. As the key is the same, you write four times the same value in your redis.
From your JSON, I guess you want to have one key per transaction in your redis: "tr1", "tr2", "tr3", "tr4". If you do:
for i in data['transactions']:
print(i)
it will print:
"tr1"
"tr2"
"tr3"
"tr4"
you can modify your existing code like this:
data=json.load(f)
for i in data['transactions']:
r.execute_command('JSON.SET', i,'.', json.dumps(data['transactions'][i]))
it will do what you want. But, there is a better way, the items function that allows you to iterates on key and values at the same time:
data=json.load(f)
for key, value in data['transactions'].items():
r.execute_command('JSON.SET', key, '.', json.dumps(value))
I let you use the @Guy Korland improvement about redis api.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ndclt |
