1

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' が存在しますか?

4

0 に答える 0