温馨提示×

怎么将json导入redis数据库

小新
475
2021-02-22 08:21:46
栏目: 云计算

怎么将json导入redis数据库

将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')))



0