2016-08-06 20 views
-1

私のjsonファイルのスニペットがあります。 Pythonを使用してこれを素敵なCSVファイルに変換する方法はありますか?テキストや感情のようなものには独自の列がありますか?JSONファイルからCSVファイルへ

{ 
    "status":"OK", 
    "totalTransactions":"1", 
    "language":"english", 
    "url":"http://well.com", 
    "results":[ 
     { 
     "text":"food", 
     "sentiment":{ 
      "score":"0.456369", 
      "type":"positive" 
     } 
     } 
    ] 
}{ 
    "status":"OK", 
    "totalTransactions":"1", 
    "language":"english", 
    "warningMessage":"truncated-oversized-text-content", 
    "url":"http://www.times.com", 
    "results":[ 
     { 
     "text":"food", 
     "sentiment":{ 
      "score":"0.678684", 
      "type":"positive" 
     } 
     } 
    ] 
} 

私はそれから特定の情報を引き出したいと思っています。私はこのコードを試しましたが、次のエラーが発生し続けます。私はそれがjsonの括弧/書式設定と関係があると思う?どうすればこのベストを解決できますか?

import json 
from pprint import pprint 

with open('data.json') as data_file:  
    data = json.load(data_file) 
pprint(data) 

ValueError: Extra data: line 15 column 2 - line 30 column 2 (char 367 - 780) 
+0

:それは、オブジェクト(辞書)と名称結果dataのリストにファイルには何が変換しようとします。どのように無効なjsonデータを修正する方法といいcsvファイルに変換する方法です。どちらかにカットするのがベストです。また、2つのサブアイテムで構成されているので、「感想」欄に何を入れるべきかを詳しく説明してください。また、「結果」はリストであるため、複数の結果が含まれている可能性があります(複数の異なるサブ項目が含まれている可能性があります)。それは可能なのですか? – martineau

答えて

0

ここでは、不適切な形式のJSONファイルの問題に対処する質問の最初の部分に対する答えを示します。あなたは、少なくとも二つの質問をしていない(とほとんどのいずれかの解決しようとする試みを作っ)している

import json 
import tempfile 

# Fix the invalid json data and load it. 
with tempfile.TemporaryFile() as temp_file: 
    temp_file.write('[\n') 
    with open('json_to_csv.json', 'rb') as data_file: 
     for line in data_file: 
      temp_file.write(line.replace('}{', '},{')) 
    temp_file.write(']\n') 
    temp_file.seek(0) # rewind 
    data = json.load(temp_file) 

print(json.dumps(data, indent=4)) # show result 
+0

ありがとう、私はそれがどこからでもエラーの原因となっていたが、このコードでそれをクリアした後、私の他の質問は解決されました。 – kkjj

+0

ようこそ。有効なJSONドキュメントは、完全に単一の[JSONタイプの値](https://en.wikipedia.org/wiki/JSON#Data_types.2C_syntax_and_example)で構成されています。しかし、この値は 'Array'または' Object'型である可能性があります。両方とも他の値を含むことができます。 – martineau

2

JSONは確かに有効ではありません、15行目で予告:}{

あなたが外/最初のオブジェクトを終了し、基本的に2つの異なるJSON文字列を連結し、新しいものを始めています。

あなたは角括弧で囲んで、それらのうちの配列を作成することができ、これを修正し、2つのオブジェクト間のカンマを追加するには:

[{ 
    "status":"OK", 
    "totalTransactions":"1", 
    "language":"english", 
    "url":"http://well.com", 
    "results":[ 
     { 
     "text":"food", 
     "sentiment":{ 
      "score":"0.456369", 
      "type":"positive" 
     } 
     } 
    ] 
},{ 
    "status":"OK", 
    "totalTransactions":"1", 
    "language":"english", 
    "warningMessage":"truncated-oversized-text-content", 
    "url":"http://www.times.com", 
    "results":[ 
     { 
     "text":"food", 
     "sentiment":{ 
      "score":"0.678684", 
      "type":"positive" 
     } 
     } 
    ] 
}] 

あなたは、この配列を反復処理することができます

import json 
from pprint import pprint 

with open('data.json') as data_file:  
    data = json.load(data_file) 
    for entry in data: 
     print "%s;%s" % (entry['url'], entry['status']) 
修正CSVで
0

chrkiが指摘したように、完全なPythonのソースは次のようになります。

#!/usr/bin/python 
import json 

with open('data.json') as data_file:  
    data = json.load(data_file) 
    out = open('out.csv', 'w+') 
    out.write("url;totalTransactions;language;status;text;score;type\n") 
    for entry in data: 
     out.write("%s;%s;%s;%s;%s;%s;%s\n" % (
      entry['url'], 
      entry['totalTransactions'], 
      entry['language'], 
      entry['status'], 
      entry['results'][0]['text'], 
      entry['results'][0]['sentiment']['score'], 
      entry['results'][0]['sentiment']['type']) 
) 
+0

エントリ['results'] [0] ['text']で[0]がどのように機能するかについてもっと知ることができますか?私は結果にKeyErrorを受け取りました。ありがとう! – kkjj

0

あなたはjsonをPython辞書にロードして正しい軌道に乗っています。 python csvモジュールを使用してcsv出力ファイルを書き込むことを検討してください。

https://docs.python.org/2/library/csv.html 

キーがヘッダー行になり、各項目に対して行を作成して入力することができます。

関連する問題