2016-03-22 4 views
0

これまでの私の以前の問題[1]を引き継いで、@ SiHaでダウンロードできたJSONファイルを解析しようとしています助けて。 JSONはそのように構成されていますJSONファイルを解析することができません。ValueError:Extra Data

{"properties": [{"property": "name", "value": "A random company name"}, {"property": "companyId", "value": 123456789}]}{"properties": [{"property": "name", "value": "Another random company name"}, {"property": "companyId", "value": 31415999}]}{"properties": [{"property": "name", "value": "Yet another random company"}, {"property": "companyId", "value": 10101010}]} 

私は少しのSiHaのコード@変性することにより、これを取得することができました:

def get_companies(): 
      create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key) 
      headers = {'content-type': 'application/json'} 
      create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers) 
      if create_get_recent_companies_response.status_code == 200: 
       while True: 
        for i in create_get_recent_companies_response.json()[u'companies']: 

         all_the_companies = { "properties": [ 
                { "property": "name", "value": i[u'properties'][u'name'][u'value'] }, 
                { "property": "companyId", "value": i[u'companyId'] } 
               ] 
              } 

         with open("all_the_companies.json", "a") as myfile: 
          myfile.write(json.dumps(all_the_companies)) 
         #print(companyProperties) 
        offset = create_get_recent_companies_response.json()[u'offset'] 
        hasMore = create_get_recent_companies_response.json()[u'has-more'] 
        if not hasMore: 
         break 
        else: 
         create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset) 
         create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers) 


      else: 
       print("Something went wrong, check the supplied field values.\n") 
       print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4)) 

だからそれは一部でした。今私は2つのものを抽出するために以下のコードを使用しようとしています:1)nameと2)companyId

#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import sys 
import os.path 
import requests 
import json 
import csv 
import glob2 
import shutil 
import time 
import time as howLong 
from time import sleep 
from time import gmtime, strftime 

# Local Testing Version 
findCSV = glob2.glob('*contact*.csv') 

theDate = time=strftime("%Y-%m-%d", gmtime()) 
theTime = time=strftime("%H:%M:%S", gmtime()) 

# Exception handling 
try: 
    testData = findCSV[0] 
except IndexError: 
    print ("\nSyncronisation attempted on {date} at {time}: There are no \"contact\" CSVs, please upload one and try again.\n").format(date=theDate, time=theTime) 
    print("====================================================================================================================\n") 
    sys.exit() 

for theCSV in findCSV: 

    def process_companies(): 
     with open('all_the_companies.json') as data_file: 
      data = json.load(data_file) 
      for i in data: 
       company_name = data[i][u'name'] 
       #print(company_name) 
       if row[0].lower() == company_name.lower(): 
        contact_company_id = data[i][u'companyId'] 
        #print(contact_company_id) 
        return contact_company_id 

       else: 
        print("Something went wrong, check the \"get_companies()\" function.\n") 
        print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4)) 

    if __name__ == "__main__": 
     start_time = howLong.time() 
     process_companies() 
     print("This operation took %s seconds.\n" % (howLong.time() - start_time)) 
     sys.exit() 
残念ながら

、そのは動作していない - 私は、次のトレースバックを取得しています:

Traceback (most recent call last): 
    File "wta_parse_json.py", line 62, in <module> 
    process_companies() 
    File "wta_parse_json.py", line 47, in process_companies 
    data = json.load(data_file) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 290, in load 
    **kw) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads 
    return _default_decoder.decode(s) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 369, in decode 
    raise ValueError(errmsg("Extra data", s, end, len(s))) 
ValueError: Extra data: line 1 column 130 - line 1 column 1455831 (char 129 - 1455830) 

私は、ファイルを開くためにjson.dumpsないjson.dumpを使用していることを確認しましたが、それでもそのていませんでしたワーキング。 :(

私は今、JSONにあきらめて、以下のコードでシンプルなCSVをエクスポートしようとしています:

def get_companies(): 
      create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key) 
      headers = {'content-type': 'application/json'} 
      create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers) 
      if create_get_recent_companies_response.status_code == 200: 
       while True: 
        for i in create_get_recent_companies_response.json()[u'companies']: 

         all_the_companies = "{name},{id}\n".format(name=i[u'properties'][u'name'][u'value'], id=i[u'companyId']) 
         all_the_companies.encode('utf-8') 

         with open("all_the_companies.csv", "a") as myfile: 
          myfile.write(all_the_companies) 
         #print(companyProperties) 
        offset = create_get_recent_companies_response.json()[u'offset'] 
        hasMore = create_get_recent_companies_response.json()[u'has-more'] 
        if not hasMore: 
         break 
        else: 
         create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset) 
         create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers) 
    [1]: http://stackoverflow.com/questions/36148346/unable-to-loop-through-paged-api-responses-with-python 

しかし、これはどちらかの権利ではないように見える - 私は」にもかかわらず、書式設定の問題をよく読んでまして、.encode('utf-8')追加を追加している私はまだ、次のトレースバックを取得し終わる:

Traceback (most recent call last): 
    File "wta_get_companies.py", line 78, in <module> 
    get_companies() 
    File "wta_get_companies.py", line 57, in get_companies 
    all_the_companies = "{name},{id}\n".format(name=i[u'properties'][u'name'][u'value'], id=i[u'companyId']) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 3: ordinal not in range(128) 
+0

JSONの例では、間違っている - それは、3つのJSONオブジェクトが一緒にマージされています。 –

+0

あなたの入力文字列には、 '{{'が部分文字列として含まれており、2つのオブジェクトの表現が一緒に実行されていることを意味します。あなたのエラーを説明するかどうか私は言うことはできませんが、それは明らかに有効ではありませんJSON – holdenweb

答えて

2

JSONデータが3つのオブジェクト次々にあり、簡素化:。

{ .. }{ .. }{ .. } 

これはJSON標準でサポートされているものではありません。 Pythonはそれをどのように解析することになっていますか?それを自動的に配列にラップしますか?それを3つの異なる変数に割り当てますか?最初のものを使うだけですか?

[{ .. },{ .. },{ .. }] 

またはフル:あなたはおそらく単純化配列、でそれをラップしたい

[{"properties": [{"property": "name", "value": "A random company name"}, {"property": "companyId", "value": 123456789}]},{"properties": [{"property": "name", "value": "Another random company name"}, {"property": "companyId", "value": 31415999}]},{"properties": [{"property": "name", "value": "Yet another random company"}, {"property": "companyId", "value": 10101010}]}] 
+0

こんにちは@Carpetsmoker、私は手作業でやってみました(上記のスクリプトで上記のコンマを自動的に追加することができなかったので、 – Marko

+0

@Marko「自己区切り」とは、JSONパーサがメッセージの終わりを判断するための助けを必要としないことを意味します。つまり、[...]を書くことができます。 '[..] END_OF_JSON'または' data is 42 bytes:[..] '。JSONオブジェクトの束を連結して一度に解析することはできません。 – Carpetsmoker

+0

清算のおかげで@Carpetsmoker、私私はJSONをあきらめて、シンプルなCSVをエクスポートしようとしていますが、これもまた問題に満ちているようです。 – Marko

関連する問題