潜心研究终于出了一个可以复用的函数:
# coding=utf-8
import json
import types
class Bjson(object):
def __init__(self):
pass
def getValue(self,json,arr):
for key in arr:
if(type(key)==types.UnicodeType):
key=str(key)
json=json[key]
return json
def upValue(self,json,arr,value):
tarr=arr[::-1]
temp=self.getValue(json,tarr[:0:-1])
keyname=tarr[0]
if(type(keyname)==types.UnicodeType):
keyname=str(keyname)
temp[keyname]=value
for i in range(1,len(tarr)):
a=i
keyname=tarr[i]
if(type(keyname)==types.UnicodeType):
keyname=str(keyname)
temp_a=self.getValue(json,tarr[:a:-1])
temp_a[keyname]=temp
temp=temp_a
return temp
怎么用呢?很简单:
json:这个是原json内容
keypath:是字段的路径
value:需要改之后的值
json={"as":[{"aa":"bb","bb":"bb","name":"zhangsan"}{"aa":"bb","bb":"bb","name":"zhangsan"}]}
keypath=["as",0,"name"]
value="lisi"
BJ=Bjson()
newjson=BJ.upValue(json,keypath,value)
输出结果是:
{"as":[{"aa":"bb","bb":"bb","name":"zhangsan"}{"aa":"bb","bb":"bb","name":"zhangsan"}]}