我一直在试图弄清楚如何将键和值设置为特定的列。我所说的列的意思是:
"fruit": {
    "american" {
        "key": "value",
        "key2": "value2"
    },
    "europe" {
        "key": "value"
        "key2": "value2"
    }
},
"books": {
    "american_author" {
        "key": "value"
        "key2": "value2"
    },
    "asia_author" {
        "key": "value"
        "key2": "value2"
    }
},
"paint": {
    "africa" {
        "key": "value"
        "key2": "value2"
    },
    "south_america" {
        "key": "value"
        "key2": "value2"
    }
}我在这里试图实现的是,我希望能够添加一个新的“列”,即水果、书籍和油漆,而在这些值中,我想添加另一个“列”,在每一列中我要添加键和值。正如您在上面的片段中所看到的。
现在我做了这样的事情:
import serialized_redis
r = serialized_redis.JSONSerializedRedis(host='localhost', port=6379, db=0)
r.set('fruit', 'american', {'key': 'value' })但回报是:
    raise DataError("Invalid input of type: '%s'. Convert to a "
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.我的问题是,我是否能够使用Redis完成这个任务?如果是,我如何才能将键和值添加到线程顶部给定的特定“列”中?
发布于 2021-02-24 14:25:16
可以使用Redis Hash将嵌套的JSON部分编码为字符串
例如,“水果”、“书籍”、“油漆”等可以是红色散列,'american','europe‘等可以是散列的键,' key ','key2’可以作为键的值存储为JSON字符串。如下所示:
redisClient = redis.Redis(host='localhost', port=6379, db=0)
# your application logic to form the json
american_json = {"key": "value", "key2": "value2"}
europe_json = {"key": "value", "key2": "value2"}
# hash name: fruit; # hash-key1: american; #value of hash-key1: JSON as string
redisClient.hset("fruit", "american", json.dumps(american_json))    
redisClient.hset("fruit", "europe", json.dumps(europe_json))如果此时检查redis:
127.0.0.1:6379> hgetall fruit
1) "american"
2) "{\"key\": \"value\", \"key2\": \"value2\"}"
3) "europe"
4) "{\"key\": \"value\", \"key2\": \"value2\"}"添加新字段的进一步代码逻辑:
# say you have to add another key-value in the key "american" for the hash "fruit"
#first we get the key stored in redis
fruit_american_json_string = redisClient.hget("fruit", "american")
#then we convert the retrieved string to JSON
JSON_object = json.loads(fruit_american_json_string)
#add your new key
JSON_object["key3"] = "value3"
#write the new JSON as string in Redis
redisClient.hset("fruit", "american", json.dumps(JSON_object))红色信息系统的最后产出:
127.0.0.1:6379> hgetall fruit
1) "american"
2) "{\"key\": \"value\", \"key2\": \"value2\", \"key3\": \"value3\"}"
3) "europe"
4) "{\"key\": \"value\", \"key2\": \"value2\"}"发布于 2021-02-24 14:26:47
您可以通过使用Hash数据类型和HSET来实现这一点。
https://stackoverflow.com/questions/66350291
复制相似问题