【问题标题】:Add "entry" to JSON File with Python使用 Python 将“条目”添加到 JSON 文件
【发布时间】:2015-05-28 11:06:36
【问题描述】:

我需要用 python 修改一个 JSON 文件。由于我是第一次使用 python(和 JSON),我阅读了一些关于它的文章,但没有完全理解它。

我设法将 JSON 作为某种数组(或列表?)导入 python。

JSON 看起来像这样:

{
  "sources":[{
    "id":100012630,
    "name":"Activity Login Page",
    "category":"NAM/Activity",
    "automaticDateParsing":true,
    "multilineProcessingEnabled":false,
    "useAutolineMatching":false,
    "forceTimeZone":true,
    "timeZone":"Europe/Brussels",
    "filters":[],
    "cutoffTimestamp":1414364400000,
    "encoding":"UTF-8",
    "pathExpression":"C:\\NamLogs\\nam-login-page.log*",
    "blacklist":[],
    "sourceType":"LocalFile",
    "alive":true
  },{
    "id":100001824,
    "name":"localWinEvent",
    "category":"NAM/OS/EventLog",
    "automaticDateParsing":true,
    "multilineProcessingEnabled":false,
    "useAutolineMatching":false,
    "forceTimeZone":false,
    "filters":[],
    "cutoffTimestamp":1409090400000,
    "encoding":"UTF-8",
    "logNames":["Security","Application","System","Others"],
    "sourceType":"LocalWindowsEventLog",
    "alive":true
  },{
    "id":100001830,
    "name":"localWinPerf",
    "category":"NAM/OS/Perf",
    "automaticDateParsing":false,
    "multilineProcessingEnabled":false,
    "useAutolineMatching":false,
    "forceTimeZone":false,
    "filters":[],
    "cutoffTimestamp":0,
    "encoding":"UTF-8",
    "interval":60000,
    "wmiQueries":[{
      "name":"NAMID Service",
      "query":"SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE Name = 'tomcat7'"
    },{
      "name":"CPU",
      "query":"select * from Win32_PerfFormattedData_PerfOS_Processor"
    },{
      "name":"Logical Disk",
      "query":"select * from Win32_PerfFormattedData_PerfDisk_LogicalDisk"
    },{
      "name":"Physical Disk",
      "query":"select * from Win32_PerfFormattedData_PerfDisk_PhysicalDisk"
    },{
      "name":"Memory",
      "query":"select * from Win32_PerfFormattedData_PerfOS_Memory"
    },{
      "name":"Network",
      "query":"select * from Win32_PerfFormattedData_Tcpip_NetworkInterface"
    }],
    "sourceType":"LocalWindowsPerfMon",
    "alive":true
  },

现在,当我得到数百个这样的文件时,我在整个目录中编写了一个 foreach:

for filename in os.listdir('./json/'):
   with open('./json/'+filename) as data_file:    
   sources = json.load(data_file)

现在我需要在源中再次使用类似 foreach 源的东西,它将一行(或一个条目或 JSON 中称为任何“行”的任何东西)添加到每个源(类似于 collectorName=fileName),然后覆盖旧的用新的文件。

JSON 将如下所示:

   {
      "sources":[{
        "id":100012630,
        "name":"Activity Login Page",
        "category":"NAM/Activity",
        "automaticDateParsing":true,
        "multilineProcessingEnabled":false,
        "useAutolineMatching":false,
        "forceTimeZone":true,
        "timeZone":"Europe/Brussels",
        "filters":[],
        "cutoffTimestamp":1414364400000,
        "encoding":"UTF-8",
        "pathExpression":"C:\\NamLogs\\nam-login-page.log*",
        "blacklist":[],
        "sourceType":"LocalFile",
        "alive":true,
        "collectorName":"Collector2910"
      },{
        "id":100001824,
        "name":"localWinEvent",
        "category":"NAM/OS/EventLog",
        "automaticDateParsing":true,
        "multilineProcessingEnabled":false,
        "useAutolineMatching":false,
        "forceTimeZone":false,
        "filters":[],
        "cutoffTimestamp":1409090400000,
        "encoding":"UTF-8",
        "logNames":["Security","Application","System","Others"],
        "sourceType":"LocalWindowsEventLog",
        "alive":true,
        "collectorName":"Collector2910"
      },{.....

我希望我能解释我的问题,如果有人可以帮助我(即使是完全不同的解决方案),我会很高兴。

提前致谢

迈克尔

【问题讨论】:

    标签: python json python-2.7


    【解决方案1】:

    这是一种方法:

    for filename in os.listdir('./json/'):
        sources = None
        with open('./json/'+filename) as data_file:    
            sources = json.load(data_file)
            sourcelist = sources['sources']
            for i, s in enumerate(sourcelist):
                sources['sources'][i]['collectorName'] = 'Collector' + str(i)
        with open('./json/'+filename, 'w') as data_file:  
            data_file.write(json.dumps(sources))
    

    【讨论】:

    • 当您的记录为s 时,为什么要sources['sources'][i]?当你有json.dump(obj, file) 时,为什么还要data_file.write(json.dumps(sources))
    • 1) 我不想修改我正在迭代的列表。 2) 它们是等价的,json.dump 方法的作用几乎相同。
    • 1.修改您正在迭代的列表仅在您向该列表添加/删除项目时才危险,而不是当您修​​改列表中已有的项目时 - 在当前情况下,sources['sources'][i] is s == True - 两个名称都指向同一个对象,真的。 2. 是的,但第二个是要编写的代码更少;)
    【解决方案2】:
    for filename in os.listdir('./json/'):
       with open('./json/'+filename) as data_file:    
           datadict = json.load(data_file)
       # At this point you have a plain python dict.
       # This dict has a 'sources' key, pointing to
       # a list of dicts. What you want is to add
       # a 'collectorName': filename key:value pair
       # to each of these dicts
       for record in datadict["sources"]:
           record["collectorName"] = filename
       # now you just have to serialize your datadict back
       # to json and write it back to the file - which is
       # in fact a single operation
       with open('./json/'+filename, "w") as data_file:    
           json.dump(datadict, data_file)
    

    【讨论】:

    • 在这个尝试中我也遇到了:ValueError: No JSON object could be decoded
    • 是 json.loads 和 json.load 的问题吗?
    猜你喜欢
    • 2020-09-07
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 2020-09-12
    • 2021-06-19
    • 2022-01-18
    相关资源
    最近更新 更多