2017-07-11 5 views
1

次のように私はsmaple.jsonを持っている:pythonのセクション内のリストを含むjsonファイルを解析するには?

{"Detail":[ 
    { 
    "DocType":"txt", 
    "Name":"hello.txt", 
    } 
    ]} 

私は「名前」フィールドaginst値を持っている必要があります。次のように私は私のスクリプトで試してみました:

file="c:/sample.json" 
for list in file: 
    if (str(list['Detail'])=='None'): 
     print("Do nothing") 
    else: 
     ana = list['Detail'] 
     val = (str(ana)[1:-1]) 
     print val 
     print val['Name'] 

をし、私は出力を得る:だから私は、「名前」フィールドの詳細を取得するものとどのように間違って何をやっている

{"DocType":"txt","Name":"hello.txt"} 
    error:print (ana['Name']) 
    TypeError: string indices must be integers 

+0

とアクセスそれをあなたは良い方法ではありません文字列としてJSONオブジェクトを処理しています。それを辞書として扱い、必要な要素にアクセスしてください。それは容易に思えるでしょう。 –

答えて

2

あなたはjsonライブラリを使用することができます行う必要があります。

import json 

with open('sample.json', 'r') as f: 
    content = json.load(f) 

name = content['Detail'][0]['Name'] 
0

この行のエラーはprint val['Name']です。 valstrタイプなので、キーベースで検索することはできません。

import json 

json_path = "c:\\sample.json" 
with open(json_path) as json_file: 
    json_dict = json.load(json_file) 

name = json_dict['Detail'][0]['Name'] 
0

使用jsonライブラリ:

あなたは

ana[0]['Name'] 
>>> 'hello.txt' 
0

JSONライブラリに以下のリンクを参照してください[https://docs.python.org/2/library/json.html]

  1. は、データをdecodetheする)
  2. 使用json.loads(JSONファイルを開きます。
  3. ヘッダ

/コード

>>> import json 
>>> with open('test.json','r') as e: 
...  data = json.loads(e.read()) 
... 
>>> data 
{u'Detail': [{u'DocType': u'txt', u'Name': u'hello.txt'}]} 
>>> data['Detail'][0]['Name'] 
u'hello.txt' 
>>> 
関連する問題