pythonjson修改嵌套内容_在Python中,如何简洁地替换json数据中的嵌套值?

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

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.

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]

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值