从JSON解析特定数据

时间:2019-02-07 17:47:55

标签: python json python-3.x

我有一个包含大量数据的JSON文件,并且我只想保留特定的数据。

我想读取文件,获取所需的所有数据,然后另存为新的JSON。

JSON是这样的:

{
    "event": [
        {
            "date": "2019-01-01",
            "location": "world",
            "url": "www.com",
            "comments": "null",
            "country": "china",
            "genre": "blues"
        },
        {
            "date": "2000-01-01",
            "location": "street x",
            "url": "www.cn",
            "comments": "null",
            "country":"turkey",
            "genre": "reds"
        },
        {...

我希望它像这样(每个事件只有日期和网址。

{
    "event": [
        {
            "date": "2019-01-01",
            "url": "www.com"
        },
        {
            "date": "2000-01-01",
            "url": "www.cn"
        },
        {...

我可以打开JSON并使用

进行读取
with open('xx.json') as f:
   data = json.load(f)
   data2=data["events"]["date"]

但是我仍然需要了解如何在新的JSON中保存所需的数据,以保持其结构

1 个答案:

答案 0 :(得分:0)

您可以使用循环理解来循环事件,并返回仅包含所需键的字典。

data = { "event": [
{
    "date": "2019-01-01",
    "location": "world",
    "url": "www.com",
    "comments": None,
    "country": "china",
    "genre": "blues",
},
{
    "date": "2000-01-01",
    "location": "street x",
    "url": "www.cn",
    "comments": None,
    "country" :"turkey",
    "genre":"reds",
}
]}

# List comprehension
data["event"] = [{"date": x["date"], "url": x["url"]} for x in data["event"]]

或者,您可以在事件列表上映射功能

keys_to_keep = ["date", "url"]
def subset_dict(d):
    return {x: d[x] for x in keys_to_keep}

data["event"] = list(map(subset_dict, data["event"]))