将复杂的Json转换为CSV

时间:2020-01-18 06:28:06

标签: python json csv

该文件来自服务器的松弛导出文件,因此结构每次都不同(如果人们对带有文本或响应的线程进行了响应)。

我尝试了几个类似的问题。但我保证我的问题有所不同。 This oneThis one tooThis one as well

示例JSON文件:

        "client_msg_id": "f347abdc-9e2a-4cad-a37d-8daaecc5ad51",
        "type": "message",
        "text": "I came here just to check <@U3QSFG5A4> This is a sample :slightly_smiling_face:",
        "user": "U51N464MN",
        "ts": "1550511445.321100",
        "team": "T1559JB9V",
        "user_team": "T1559JB9V",
        "source_team": "T1559JB9V",
        "user_profile": {
            "avatar_hash": "gcc8ae3d55bb",
            "image_72": "https:\/\/secure.gravatar.com\/avatar\/fcc8ae3d55bb91cb750438657694f8a0.jpg?s=72&d=https%3A%2F%2Fa.slack-edge.com%2Fdf10d%2Fimg%2Favatars%2Fava_0026-72.png",
            "first_name": "A",
            "real_name": "a name",
            "display_name": "user",
            "team": "T1559JB9V",
            "name": "name",
            "is_restricted": false,
            "is_ultra_restricted": false
        },
        "thread_ts": "1550511445.321100",
        "reply_count": 3,
        "reply_users_count": 3,
        "latest_reply": "1550515952.338000",
        "reply_users": [
            "U51N464MN",
            "U8DUH4U2V",
            "U3QSFG5A4"
        ],
        "replies": [
            {
                "user": "U51N464MN",
                "ts": "1550511485.321200"
            },
            {
                "user": "U8DUH4U2V",
                "ts": "1550515191.337300"
            },
            {
                "user": "U3QSFG5A4",
                "ts": "1550515952.338000"
            }
        ],
        "subscribed": false,
        "reactions": [
            {
                "name": "trolldance",
                "users": [
                    "U51N464MN",
                    "U4B30MHQE",
                    "U68E6A0JF"
                ],
                "count": 3
            },
            {
                "name": "trollface",
                "users": [
                    "U8DUH4U2V"
                ],
                "count": 1
            }
        ]
    },

问题在于,有几个键会有所不同,因此消息之间的同一json文件中的结构会根据其他用户与给定消息的交互方式而变化。

1 个答案:

答案 0 :(得分:0)


with open("file.json") as file:
    d = json.load(file)

df = pd.io.json.json_normalize(d)

df.columns = df.columns.map(lambda x: x.split(".")[-1])