python - 将嵌套的 json(mixpanel api 原始数据导出)转换为 CSV? (最好在 Python 中)

标签 python json excel csv mixpanel

我已经收到来自 Mixpanel API 的原始数据。我希望将其转换为 CSV 文件,以便我可以在 Excel 中操作数据。我试过这个在线工具 ( http://jsfiddle.net/sturtevant/vUnF9/ ),但它似乎无法处理嵌套的 json 结果。做这个的最好方式是什么?

这是示例输出:

{"event":"Event.Name","properties":{"time":1376784014,"distinct_id":"distinctID","$app_version":"1.XX","$city":"cityName","$ios_ifa":"iosIfa","$lib_version":"X.Y.Z","$manufacturer":"Apple","$model":"model","$os":"iPhone OS","$os_version":"X.Y.Z","$region":"Region","$screen_height":999,"$screen_width":999,"$wifi":true,"App Version":"1.XX","BattleDuration":"99","BattleNum":"2","Episode Num":"2","PlayerVictory":"1","mp_country_code":"CODE","mp_device_model":"Model","mp_lib":"iphone"}}

最佳答案

我猜这只是您可能要处理的众多记录之一。基本上,您需要将 JSON 对象转换为更扁平的对象,无需嵌套,同时又不会丢失键及其关系。

这...

{
    "event":"Event.Name",
    "properties":{
        "time":1376784014,
        "distinct_id":"distinctID",
    ....
    ....
}

可以转换为...(您可以将 _ 替换为任何其他分隔符)

{
    "mixpanel_event":"Event.Name",
    "mixpanel_properties_time":"1376784014",
    "mixpanel_properties_distinct_id":"distinctID",
    ....
    ....
}

然后,您可以使用 csv.DictWriter 将此结构写入 csv 文件。

你可以像这样使用递归函数......

def reduce_item(key, value):
    global reduced_item

    #Reduction Condition 1
    if type(value) is list:
        i=0
        for sub_item in value:
            reduce_item(key+'_'+str(i), sub_item)
            i=i+1

    #Reduction Condition 2
    elif type(value) is dict:
        sub_keys = value.keys()
        for sub_key in sub_keys:
            reduce_item(key+'_'+str(sub_key), value[sub_key])

    #Base Condition
    else:
        reduced_item[str(key)] = str(value)

然后你可以这样调用这个函数......

raw_data = json.loads("your_json_string")
reduced_item = {}
reduce_item("mixpanel", raw_data)

我已经编写了一个脚本来执行此操作。完整代码可以看Github .可以找到详细的解释here .

关于python - 将嵌套的 json(mixpanel api 原始数据导出)转换为 CSV? (最好在 Python 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18349562/

相关文章:

python - 如何在 Linux 中跟踪所有后代进程

python - 如何获取多个模型中的最新条目 - django python

ios - 将 “correct” 数据从 UITableViewController 中的选定单元格传递到 ViewController

excel - 加载过程中以下区域出现问题: Table

excel - 在多行Excel单元格中的特殊字符后提取文本

c# - Python 到 C# 的 RGBA 值转换不起作用

python - 如何让 setuptools 忽略颠覆 list ?

java - 仅当键存在时才向 ArrayList 添加数据

javascript 复杂递归

excel - 使用宏对表格进行排序