如何从JSON文件中提取特定数据

时间:2013-10-26 13:17:50

标签: json

我有这个数据库http://ashleyw.co.uk/project/food-nutrient-database,我想将组Dairy and Egg Products解压缩到一个单独的Json文件中。

此外,在该组内部,一些数据是三重的。例如:

{
    "id": 1008,
    "description": "Cheese, caraway",
    "tags": [],
    "manufacturer": "",
    "group": "Dairy and Egg Products",
    "portions": [
        {
            "amount": 1,
            "unit": "oz",
            "grams": 28.35
        }
    ],
    "nutrients": [
        {
            "value": 25.18,
            "units": "g",
            "description": "Protein",
            "group": "Composition"
        },
        {
            "value": 29.2,
            "units": "g",
            "description": "Total lipid (fat)",
            "group": "Composition"
        },
        {
            "value": 3.06,
            "units": "g",
            "description": "Carbohydrate, by difference",
            "group": "Composition"
        },
        {
            "value": 25.18,
            "units": "g",
            "description": "Protein",
            "group": "Composition"
        },
        {
            "value": 29.2,
            "units": "g",
            "description": "Total lipid (fat)",
            "group": "Composition"
        },
        {
            "value": 3.06,
            "units": "g",
            "description": "Carbohydrate, by difference",
            "group": "Composition"
        },
        {
            "value": 25.18,
            "units": "g",
            "description": "Protein",
            "group": "Composition"
        },
        {
            "value": 29.2,
            "units": "g",
            "description": "Total lipid (fat)",
            "group": "Composition"
        },
        {
            "value": 3.06,
            "units": "g",
            "description": "Carbohydrate, by difference",
            "group": "Composition"
        }
    ]
}

nutrients节点的每个子节点都是三重的。怎么能剥夺额外的东西?

1 个答案:

答案 0 :(得分:0)

使用Python

import json

with open("data.json") as f, open("nutrients.json", "w") as g:
    d = json.loads(f.read())
    json.dump(d["nutrients"], g)