0

このコレクションのやり方を教えてください。問題は次のとおりです。次のことを想定する JSON を取得します。

[{
    "pk": 1,
    "model": "store.book",
    "fields": {
        "name": "Mostly Harmless",
        "author": ["Douglas", "Adams"]
    }
}]

次に、ファイルを解凍してデータを保存し、ファイルを閉じます。次回(これはサイクルです)、JSONのように再度受信します。たとえば、次のようになります

[{
    "pk": 2,
    "model": "store.book",
    "fields": {
        "name": "Henry",
        "author": ["Hans"]
    }
}]

2 番目の JSON は、最初の JSON と同じファイルに配置する必要があります。ここで問題が発生します。この段階では、次のようにします。括弧を削除してコンマを挿入します。この作業のためのよりスマートでより良い方法はありますか?

用途の JSON シリアライズ Django オブジェクトの作成。彼らのアイデアを共有していただければ幸いです。

PS: 最小限のメモリを使用することが重要です。ファイルが約 50 ~ 60 GB で、メモリ内に最大約 1 GB を保持すると仮定します。

4

3 に答える 3

0

マルチギガバイトのオブジェクトを作成しないようにするために、各オブジェクトを別々の行に格納できます。フォーマットに改行を使用せずに各オブジェクトをダンプする必要があります (json 文字列自体は\n通常どおり (2 文字) を使用できます)。

import json

with open('output.txt', 'a') as file: # open the file in the append mode
    json.dump(obj, file, 
              separators=',:') # the most compact representation by default
    file.write("\n")
于 2014-03-30T20:07:58.123 に答える
0

JSON を保存するだけなので、JSON を解析する必要はありません。次の (a) ファイルを作成し、(b) 各サイクルでファイルにテキストを追加します。

from os.path import getsize

def init(filename):
    """
    Creates a new file and sets its content to "[]".
    """
    with open(filename, 'w') as f:
        f.write("[]")
        f.close()

def append(filename, text):
    """
    Appends a JSON to a file that has been initialised with `init`.
    """
    length = getsize(filename) #Figure out the number of characters in the file
    with open(filename, 'r+') as f:
        f.seek(length - 1) #Go to the end of the file
        if length > 2: #Insert a delimiter if this is not the first JSON
            f.write(",\n")
        f.write(text[1:-1]) #Append the JSON
        f.write("]") #Write a closing bracket
        f.close()

filename = "temp.txt"
init(filename)

while mycondition:
    append(filename, getjson())

各サイクルの後に JSON を保存する必要がない場合は、次のことができます。

jsons = []
while mycondition:
    jsons.append(getjson()[1:-1])

with open("temp.txt", "w") as f:
    f.write("[")
    f.write(",".join(jsons))
    f.write("]")
    f.close()
于 2014-03-28T12:41:04.703 に答える