將json導入redis數據庫的示例:
使用python3將json對象導入redis數據庫。
json對象
var someexpert={
id:10000
realname: ‘expert-a’
organization:’BUAA’
}
var frameworks=[
‘vue’,
‘react’,
‘angular’
]
通過以下程序代碼將其導入redis數據庫。
# -*- coding=utf-8 -*-
"""
description:
將json對象存入Redis
"""
import json
import redis
class RedisTT(object):
def __init__(self):
self.host = 'localhost'
self.port = '6379'
self.r = redis.StrictRedis(host=self.host, port=self.port)
def insertRedis(self, keyName, jsonStr): # 存入到redis中
self.r.lpush(keyName, jsonStr)
def save1():
someexpert = {}
someexpert['id'] = 10000
someexpert['realname'] = 'expert-a'
someexpert['organization'] = 'BUAA'
if RedisTT().r.exists('someexpert'):
RedisTT().r.delete('someexpert') # 刪除key為someexpert的鍵值對
RedisTT().insertRedis(keyName='someexpert', jsonStr=json.dumps(someexpert))
def save2():
frameworks = ['vue', 'react', 'angular']
if RedisTT().r.exists('frameworks'):
RedisTT().r.delete('frameworks') # 刪除key為frameworks的鍵值對
RedisTT().insertRedis(keyName='frameworks', jsonStr=json.dumps(frameworks))
if __name__ == "__main__":
save1()
save2()
print(RedisTT().r.lrange('someexpert', 0, RedisTT().r.llen('someexpert')))
print(RedisTT().r.lrange('frameworks', 0, RedisTT().r.llen('frameworks')))