在Python中,如何简洁地替换json数据中的嵌套值? [英] In Python, how to concisely replace nested values in json data?
问题描述
这是对在Python中,如何简洁地获取json数据中的嵌套值的扩展?
我从JSON加载了数据,并尝试使用列表作为输入替换任意嵌套值,其中该列表与后继子代的名称相对应.我想要一个函数 replace_value(data,lookup,value),该函数通过将查找中的每个条目视为嵌套子项来替换数据中的值.
I have data loaded from JSON and am trying to replace arbitrary nested values using a list as input, where the list corresponds to the names of successive children. I want a function replace_value(data,lookup,value) that replaces the value in the data by treating each entry in lookup as a nested child.
这是我要执行的操作的结构:
Here is the structure of what I'm trying to do:
json_data = {'alldata':{'name':'CAD/USD','TimeSeries':{'dates':['2018-01-01','2018-01-02'],'rates':[1.3241,1.3233]}}}
def replace_value(data,lookup,value):
DEFINITION
lookup = ['alldata','TimeSeries','rates']
replace_value(json_data,lookup,[2,3])
# The following should return [2,3]
print(json_data['alldata']['TimeSeries']['rates'])
我能够从get_value()开始,但是对如何进行替换感到困惑.我不固定于此代码结构,但希望能够以编程方式替换给定连续子项列表和要替换的值的数据中的值.
I was able to make a start with get_value(), but am stumped about how to do replacement. I'm not fixed to this code structure, but want to be able to programatically replace a value in the data given the list of successive children and the value to replace.
注意:查找的长度可能为1
Note: it is possible that lookup can be of length 1
推荐答案
按照查找进行操作,直到我们排在第二位为止,然后将值分配给当前对象中的最后一次查找
Follow the lookups until we're second from the end, then assign the value to the last lookup in the current object
def get_value(data,lookup): # Or whatever definition you like
res = data
for item in lookup:
res = res[item]
return res
def replace_value(data, lookup, value):
obj = get_value(data, lookup[:-1])
obj[lookup[-1]] = value
json_data = {'alldata':{'name':'CAD/USD','TimeSeries':{'dates':['2018-01-01','2018-01-02'],'rates':[1.3241,1.3233]}}}
lookup = ['alldata','TimeSeries','rates']
replace_value(json_data,lookup,[2,3])
print(json_data['alldata']['TimeSeries']['rates']) # [2, 3]
如果您担心列表副本lookup[:-1]
,可以将其替换为迭代器切片:
If you're worried about the list copy lookup[:-1]
, you can replace it with an iterator slice:
from itertools import islice
def replace_value(data, lookup, value):
it = iter(lookup)
slice = islice(it, len(lookup)-1)
obj = get_value(data, slice)
final = next(it)
obj[final] = value
这篇关于在Python中,如何简洁地替换json数据中的嵌套值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!