【问题标题】:Count unique values in objects within large JSON file with Python使用 Python 计算大型 JSON 文件中对象中的唯一值
【发布时间】:2017-09-09 02:11:44
【问题描述】:

我有一些相当大的 JSON 文件。每个都包含一 (1) 个数组中的数千个对象。 JSON 的结构如下:

{
    "alert": [
    { "field1": "abc",
    "field2": "def",
    "field3": "xyz
},
{ "field1": null,
"field2": null,
"field3": "xyz",
},
...
...
]

使用 Python 和 json 库搜索 JSON 文件、查找数组中每个对象中的唯一值并计算它们出现的次数的最有效方法是什么?例如,在数组的“field3”对象中搜索值“xyz”并计算它出现的次数。我尝试了一些基于 StackOverflow 中现有解决方案的变体,但它们没有提供我正在寻找的结果。

【问题讨论】:

    标签: json python-2.7


    【解决方案1】:

    出现了关于 PyPI 的快速搜索

    这是一个适用于您的数据的示例

    import ijson
    
    counts = {}
    with file("data.json") as f:
        objects = ijson.items(f, 'alert.item')
        for o in objects:
            for k, v in o.items():
                field = counts.get(k,{})
                total = field.get(v,0)
                field[v] = total + 1
                counts[k] = field
    
    import json
    print json.dumps(counts, indent=2)
    

    使用data.json 中的示例数据运行此程序会产生

    {
      "field2": {
        "null": 1, 
        "def": 1
      }, 
      "field3": {
        "xyz": 2
      }, 
      "field1": {
        "null": 1, 
        "abc": 1
      }
    }
    

    但请注意,您输入中的 null 已转换为字符串“null”。

    作为比较,这里有一个jq 命令,它使用tostream 产生等效结果

     jq -M '
        reduce (tostream|select(length==2)) as [$p,$v] (
          {}
        ; ($p[2:]+[$v|tostring]) as $k
        | setpath($k; getpath($k)+1)
        )
    ' data.json
    

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 2021-01-02
      • 2017-07-24
      相关资源
      最近更新 更多