Pandas json_normalize 嵌套 JSON

Pandas json_normalize with nested JSON

我尝试了很多替代方案,更好的结果是这个声明:

json_normalize(a['solution'][0]['tour'])

我一次只能看到一个街区的游览。 vehicle_id 0 条信息,我需要它们。谢谢。

JSON是:

{
    "total_clusters": 6,
    "solution": [
        {
            "vehicles_id": "0",
            "vehicles_location": {
                "lat": "",
                "lng": ""
            },
            "tour": [
                {
                    "shipping_id": "4a4b0750-63a7-11ea-8955-43fcb2cd860a",
                    "type": "dropoff",
                    "location_id": "797",
                    "coordinates": {
                        "lat": "-34.545736",
                        "lng": "-58.488340"
                    },
                    "cluster": 0
                },
                {
                    "shipping_id": "75e5a2c0-6314-11ea-b657-ddd473c629a3",
                    "type": "dropoff",
                    "location_id": "114",
                    "coordinates": {
                        "lat": "-34.568707",
                        "lng": "-58.452963"
                    },
                    "cluster": 0                 
                }
            ]
        },
        {
            "vehicles_id": "1",
            "vehicles_location": {
                "lat": "",
                "lng": ""
            },
            "tour": [
                {
                    "shipping_id": "c83ac7c0-51c4-11ea-9aef-973de7785221",
                    "type": "pickup",
                    "location_id": "687",
                    "coordinates": {
                        "lat": "-34.592824",
                        "lng": "-58.375457"
                    },
                    "cluster": 1
                },
                {
                    "shipping_id": "b5a295c0-51c4-11ea-b36d-651ee769ca89",
                    "type": "pickup",
                    "location_id": "687",
                    "coordinates": {
                        "lat": "-34.592824",
                        "lng": "-58.375457"
                    },
                    "cluster": 1            
                }
            ]
        }
    ]
}

期望的输出

您需要将 record_path 参数传递给 json_normalize

来自docs

record_path : str or list of str, default None

Path in each object to list of records. If not passed, data will be assumed to be an array of records.

import pandas as pd
import json

raw_json_data = """{contents_of_your_json_here}"""
json_data = json.loads(raw_json_data)

df = pd.json_normalize(json_data, ["solution", "tour"])

结果: