我正在尝试将从 facebook 的图形 API 返回的 json 解析写入 csv,并且当字典在列表中时无法获取键的值。我使用的代码如下:
import json
import csv
import urllib
import win32com.client
# Start Excel
xlApp = win32com.client.Dispatch( "Excel.Application" )
workbook = xlApp.Workbooks.Open( 'C:\AAAA - Report\WWWWorkflow\IO listcsv.xlsm' )
sheet = workbook.Sheets( 'Sheet1' )
sheet.Activate( )
# Get values
spam = sheet.Cells( 2, 2 ).Value
default = 'none'
Ad_account_id = spam
target_url = "https://graph.facebook.com/act_" + Ad_account_id + "/adgroups?fields=id,targeting&limit=10000&access_token=blah"
json_data = urllib.urlopen(target_url)
data = json.load(json_data)
data = data["data"]
f=csv.writer(open('C:/AAAA - Report/WWWWorkflow/adid.csv','wb+'))
f.writerow(["id", "country", "age max", "keywords", "BCT"])
# the .get helps in tackling the keyerror which is when a value is missing in page type, etc.
delimiter = ', '
for item in data:
f.writerow([item.get('id','none'), delimiter.join(item.get('targeting').get("countries","none")), item.get('targeting').get('age_max','none'), delimiter.join(item.get('targeting').get("keywords","none")).encode('utf-8'), delimiter.join([str(item) for item in item.get('targeting').get("user_adclusters",'none')])])
# Goodbye Excel
workbook.Save( )
workbook.Close( )
xlApp.Quit( )
我得到的示例 JSON 响应如下:
{
"targeting": {
"genders": [
1
],
"age_max": 65,
"age_min": 25,
"countries": [
"NZ"
],
"user_adclusters": [
{
"id": "6004941354772",
"name": "Engaged Gamers - Casino"
},
{
"id": "6004948896772",
"name": "Virtual Goods - Engaged"
},
{
"id": "6004948896972",
"name": "Virtual Goods - Active"
}
],
"page_types": [
"mobile"
],
"user_os": [
"iOS_ver_4.0_and_above"
]
},
"id": "6008104890350"
},
谁能帮我只获得“user_adclusters”的名称,它是格式化的(即所有文本都存在u'?