2016-09-30 7 views
0
this is my code: 
     import json 
     from pprint import pprint 

     with open('unAnsQuestions.json') as data_file:  
      data = json.load(data_file) 
     print(len(data)) 
     json_len = len(data) 
     json_len+=1 
     with open('unAnsQuestions.json', "a") as json_file: 
      json.dump({'id':json_len,'fileName':'yogesh'},json_file,indent=2) 
      #json_file.write("{}\n".format(json.dumps(json_len))) 


         [{ 
         "id":1, 
         "text":"hey?", 
         "answer":"hi" 
         }, 
         { 
         "id":2, 
         "text":"bye.?", 
         "answer":"see you" 
        }] 
  • ウェルフォーマットパイソンを取得idと 別のファイル名です。次はjson構造です。 データを追加します。 - jsonファイルに値を追加します。 - 私はいくつかのデータを含むQuestion.jsonを持っています:
    しかし、私はこの出力を得るいくつかの値を追加するつもりです これは適切なformat.Iでこの値をブラケット '[]'。アペンドJSON値ではなく、これはJSONのfile.firstに2つの値を追加私のコードです

       [{ 
            "id":1, 
            "text":"hey?", 
            "answer":"hi" 
            }, 
            { 
            "id":2, 
            "text":"bye.?", 
            "answer":"see you" 
           }] 
           { 
           "id": 3, 
           "text":"bye.?", 
           "answer":"see you" 
            } 
    
        so, the "]" is not well formatted. I tried many times but I didn't get output.can you please tell me the exact way? 
    
+0

コードを投稿してください –

答えて

1

データは、ファイル内のオブジェクトの配列として格納されています。 ダンプする前にデータをアレイに追加する必要があります。 追加した後、ファイルを書き換え、つまりデータ変数をダンプする必要があります。

import json from pprint 
import pprint 
with open('unAnsQuestions.json') as data_file: 
    data = json.load(data_file) 
    print(len(data)) 
    json_len = len(data) 
    json_len+=1 
    with open('unAnsQuestions.json', "w") as json_file: // write the file not append to it 
    data.append({'id':json_len,'fileName':'yogesh'}) // add data in array at last index 
    json.dump(data,json_file,inde‌​nt=2) // dump the array 
    #json_file.write("{}\n".format(json.dumps(json_len))) 
+0

こんにちは、その作業。 –

+0

ありがとうございます –

0

基本的なPythonチュートリアルを見つけて読んでください。どのように動作するかについていくつかの誤解があるようです(たとえば、json_lenに1を追加しますが、そのようにするとdataには影響しません)。

単にappend()使用し、すでに読んだデータに要素を追加するには:その後

data.append({'id':3, 'text': 'buh-bye', 'answer':'huh?'}) 

を、json_file.write(json.dumps(data))は、ファイルへの新しい要素になります。

+0

ya私はそれを使用しましたが、どのようにしてidを増やすべきですか? –

+0

と私は新しいIDを入力したくないたびに、このIDを使用して+毎回IDを書く必要はありません –

関連する問題