无法替换json对象中的参数值

时间:2019-07-07 07:31:50

标签: python

我正在尝试替换json对象中的varaible值,但我无法执行此操作。我想替换json_input varaible中的datetime值,但到目前为止datetime已被串联

json_input='{"provider_code":"test","provider_resource_id":{"name":"test","value":"test"},"provider_account":"123","kpis":[{"kpi":"kpis","value":"80","unit":"%","datetime":""}]}'


newjson = {}
try:
    decoded = json.loads(json_input)

    # Access data
    for x in decoded['kpis']:
         if not (x['datetime']):
               x['datetime']="2019-07-05T18:17:08.257Z"
             newjson=json_input+x['datetime']
except (ValueError, KeyError, TypeError):
    print("JSON format error")
print(newjson)
*Actual*
new json = {"provider_code":"aws","provider_resource_id":{"name":"app_arn","value":"arn:aws:elasticbeanstalk:us-east-1:802878444238:application/mcms-eb-test"},"provider_account":"802878444238","kpis":[{"kpi":"aws.elasticbeanstalk.health_status","value":"80","unit":"%","datetime":""}]}2019-07-05T18:17:08.257Z

*Expected*
new json='{"provider_code":"test","provider_resource_id":{"name":"test","value":"test"},"provider_account":"123","kpis":[{"kpi":"kpis","value":"80","unit":"%","datetime":"2019-07-05T18:17:08.257Z"}]}'

2 个答案:

答案 0 :(得分:0)

Int

答案 1 :(得分:0)

您的问题似乎是您确实想将json_input写为newjsondecoded时写newjsondecoded是您要修改的对象。 json_input永远不会被修改,它仅用于在Python中创建JSON表示形式。此外,+x['datetime']并不能解决任何问题,可能是导致newjson末尾增加日期时间的原因。

尝试使用newjson=json_input+x['datetime']代替newjson = decoded.dumps()