【问题标题】:I would like to add another parameter to json file using python script我想使用 python 脚本向 json 文件添加另一个参数
【发布时间】:2017-07-17 21:12:03
【问题描述】:

返回

"messages": [  
    {  
        "text": "testing",   
        "ts": "1479967441.000004",   
        "user": "ray",   
        "type": "message",   
        "bot_id": "B379PT5AT"  
    },    
    {  
        "text": "SWAT start",   
        "type": "message",   
        "user": "john",   
        "ts": "1479967379.000003"  
    },   
    {  
        "text": "SWAT close",   
        "type": "message",   
        "user": "ray",    
        "ts": "1479967379.000003"  
    },   

我想添加另一个参数

"messages": [  
    {   
        "text": "testing",   
        "ts": "1479967441.000004",   
        "user": "ray",   
        "type": "message",   
        "bot_id": "B379PT5AT"  
        "icon": "URL...."  
    },   
    {  
        "text": "SWAT start",   
        "type": "message",   
        "user": "john",   
        "ts": "1479967379.000003"  
        "icon": "URL...."  
    },   
    {  
        "text": "SWAT close",   
        "type": "message",   
        "user": "ray",   
        "ts": "1479967379.000003"  
        "icon": "URL...."  
    },

代码:

import simplejson  
with open ('automation.json')as json_data:  
    data = simplejson.loads(json_data)  
    for r in  data['messages']:  
        key = messages['icon']  
        messages["icon"] = ("testing")  

outdata = simplejson.dumps(data)  

【问题讨论】:

  • 每个对象的图标字段是否相同?如果没有,那么您从哪里获得这些信息?
  • 我有一个 json 文件,我想运行一个 python 脚本,以便进行上述更改
  • @AjayGupta 这将是我将运行的命令的结果
  • @omri_saadon 我已经做出了改变,结果出来了
  • 您应该先展示自己的代码并尝试 - Stackvoerflow 不是编码服务。展示您的工作,展示您迄今为止的尝试 - 然后我们很乐意提供帮助。

标签: python json python-3.x


【解决方案1】:

你几乎拥有它。循环遍历data['messages'] 会访问一个字典列表,这就是为什么你的分配不太有效的原因。您必须先访问字典,然后再分配。

 import json
 with open('automation.json') as data_file:
     data = json.load(data_file)['messages'] # you now have a the json as a python object.
 # If you want to always add the same value to each dictionary
 data = {d['icon'] = 'A Value you want' for d in data} # d represents a dictionary in data['messages']

 # other wise, lets say the icon is linked to the user:
 icon_urls = {'john': 'http://someurl.com', 'ray': 'http://someotherurl.com'}
 data = {d['icon'] = icon_urls[d['user']] for d in data}

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 1970-01-01
    • 2021-04-17
    • 2013-05-05
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多