将嵌套的JSON(mixpanel API原始数据导出)转换为CSV? (理想的Python)

我已经收到来自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":"XYZ","$manufacturer":"Apple","$model":"model","$os":"iPhone OS","$os_version":"XYZ","$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"}} 

我猜这只是你可能处理的很多logging中的一个。 基本上,你需要将你的JSON对象转换成一个平坦的对象,而不是嵌套,而不会丢失键和关系。

这个…

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

可以转换为…(您可以用其他分隔符replace_)

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

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

你可以使用像这样的recursion函数…

 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上的完整代码。 详细的解释可以在这里find。

你可以尝试像下面给出的示例代码。 您可以使用recursion函数来获取键和值(您必须以某种方式确保顺序保持不变)

 import sys import json def getKeys(newDict): retv = [] for key in newDict.keys(): try: keyForEmbeddedDict = newDict[key].keys() retv.extend(getKeys(newDict[key])) except AttributeError: retv.append(key) return retv def getValues(newDict): retv = [] for key in newDict.keys(): try: keyForEmbeddedDict = newDict[key].keys() retv.extend(getValues(newDict[key])) except AttributeError: retv.append(newDict[key]) return retv def main(): t = {} filename = '' # Add your filename with open(filename) as f: t = json.load(f) keys = getKeys(t) result = getValues(t) print keys print result return if __name__ == '__main__': main() sys.exit(0)