Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import a .json file to redis db via redis-py

Tags:

python

json

Say I have this json code

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

How could I store it to a redisdb via redis-py?

My code is the following (I believe it's wrong):

import json
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=1)
with open('json_test.json', encoding='utf-8') as data_file:
    test_data = json.loads(data_file.read())
r.hmset('test_json', test_data)
like image 629
user3590899 Avatar asked Dec 30 '25 21:12

user3590899


1 Answers

Considering your code, and simplicity of requirement: Store JSON file content on redis, your can use simple SET for it.

To improve data parsing, it is not necessary to use .read() method over file pointer, consequently, you use json.load(fp) method version.

import json
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=1)
with open('json_test.json') as data_file:
    test_data = json.load(data_file)
r.set('test_json', test_data)
like image 124
Andre Pastore Avatar answered Jan 06 '26 12:01

Andre Pastore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!