2017-10-14 6 views
0

私は、ユーザー名を取得するより大きなプロジェクトに関してこのコードを作成しています。名前に基づいて、PythonでTkinterを使用して過去の重みを過去の人に表示します。私はちょうど私が人名を取得し、名前に応じて彼らの体重を格納する場所に動作させたこのサンプルコードを取得しようとしています。現在は、既存のIDに加重を加えるのではなく、同じ人の新しいIDを作成します。どのようにIDが既に存在する場合は追加するのではなく、既存のIDに加重を加えるだけでよいのですか?IDに基づいてJson辞書に特定の要素を追加するにはどうすればよいですか?

import json 
ID = raw_input('What is your name?') 
weight = raw_input('What is your weight?') 
data = {'People': [{'name': ID, 'weight':weight}]} 

with open('data.json', 'a+') as outfile: 
    storage = data 
    storage({'weight': weight}) 
    json.dump(storage, outfile, sort_keys=True, indent=4) 

それが現在読み取ります

{ 
    "People": [ 
     { 
      "name": "Bob", 
      "weight": "124" 
     } 
    ] 
}{ 
    "People": [ 
     { 
      "name": "Jerry", 
      "weight": "111" 
     } 
    ] 
}{ 
    "People": [ 
     { 
      "name": "Bob", 
      "weight": "130" 
     } 
    ] 
} 

を私は私が得ることができるよう、以下のコードに近い形式にそれを取得したいのですが:

}{ 
    "People": [ 
     { 
      "name": "Jerry", 
      "weight": "111" 
     } 
    ] 
}{ 
    "People": [ 
     { 
      "name": "Bob", 
      "weight": "130", "124" 
     } 
    ] 
} 

私はついて行くアムこれは間違っている?私は入力された特定のIDだけのファイルを読み込み、新しいものを記録した後に既存の重みを表示することを望んでいました。例えば、コードが実行された後、「Bob」の重みのすべてが表示されます。私はかなりjsonに新しいので、これはより効率的な方法がある場合、私はすべての耳です!

答えて

0

まず、あなたがあなたのdata.jsonファイルが有効なJSONコンテンツを含んで行う必要があり、私はあなたのdata.jsonのようなことを行うことができますお勧め:

{ 
    "People": [ 
     { 
      "name": "Bob", 
      "weight": [ 
       "124", 
       "130" 
      ] 
     }, 
     { 
      "name": "Jerry", 
      "weight": [ 
       "111" 
      ] 
     } 
    ] 
} 

第二に、あなたのようにJSONファイルと負荷を開くことができますあなたはそれを操作することができます。 nameを見つけてweightをリストに追加する場合は、新しい名前の場合は、nameweightの全体を追加します。以下はコードです

import json 
ID = raw_input('What is your name?') 
weight = raw_input('What is your weight?') 
data = {'People': [{'name': ID, 'weight':[weight]}]} 

with open('data.json') as outfile_r: 
    try: 
     source_data = json.load(outfile_r) 
     new_name = True 
     for ppl in source_data['People']: 
      if ppl['name']==ID: 
       ppl['weight'].append(weight) 
       new_name = False 
     if new_name: 
      source_data['People'].append({'name': ID, 'weight':[weight]}) 
     storage = source_data 
    except: 
     storage = data 
with open('data.json','w') as outfile_w: 
    json.dump(storage, outfile_w, sort_keys=True, indent=4) 
+0

ありがとうございます!それはもっと意味がある、まだjsonとpythonを知ることになる – aRandomViking

0

ちょうど追加するのではなく、まずデータを読み込み、そのユーザーが既に存在するかどうかを確認してから、データを追加して保存してみてください。

import json 
ID = raw_input('What is your name?') 
weight = raw_input('What is your weight?') 
data = {'People': [{'name': ID, 'weight':weight}]} 

with open('data.json', 'w+') as outfile: 
    parsed_json = json.loads(outfile) 
    ppl = parsed_json['People'] 
    try: 
     person = ppl[ID] 
     person['weight'] = weight 
    except: 
     ppl += { "name": ID, "weight": weight } 
    storage(ppl) 
    json.dump(storage, outfile, sort_keys=True, indent=4) 
関連する問題