【问题标题】:The collection of some JSON data into a file将一些 JSON 数据收集到一个文件中
【发布时间】:2014-03-28 12:03:46
【问题描述】:

你能告诉我如何做这个集合吗?问题是这样的:我让 JSON 假设以下内容

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

然后解压一个文件我保存数据并关闭文件,下次(这是一个循环)再次像JSON一样接收,例如,如下

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

第二个 JSON 必须放入它所在的文件和第一个文件中。怎么办的问题来了。在这个阶段,我是按照以下方式进行的,删除括号并放入逗号。有没有更聪明更好的方法来完成这项工作?

Creating JSON-Serializing Django 对象的一种使用。如果您能分享他们的想法,我将不胜感激。

PS:使用最少的内存很重要。假设文件大约 50-60 GB 并且在内存中最多可以容纳大约 1 GB

【问题讨论】:

  • 您想将 JSON 数据融合到一个文件中吗?使用 json 库将每条 JSON 数据转换为 Python 对象,然后在新对象中相互融合,最后再次使用库将其保存在文件中。看看这里:docs.python.org/2/library/json.html 或这里docs.python.org/3.4/library/json.html
  • 这表示你会把所有的数据都保存在内存中,因为数据很怕Out of Memory

标签: python json django serialization django-serializer


【解决方案1】:

您必须将数据转换为 JSON 并将其存储到文件中。然后再次从文件中读取并将新数据附加到对象并再次将其保存到文件中。以下是一些可能对您有用的代码:

使用 JSON。文档位于 - http://docs.python.org/2/library/json.html

第一次写入文件时,可以使用类似:

>>> import json
>>> fileW = open("filename.txt","w")
>>> json1 = [{
...     "pk": 1,
...     "model": "store.book",
...     "fields": {
...         "name": "Mostly Harmless",
...         "author": ["Douglas", "Adams"]
...     }
... }]
>>> json.dump(json1, fileW)
>>> fileW.close()

以下代码可用于循环读取文件并向其添加数据。

>>> fileLoop = open("filename.txt","r+")
>>> jsonFromFile = json.load(fileLoop)
>>> jsonFromFile
[{u'pk': 1, u'model': u'store.book', u'fields': {u'name': u'Mostly Harmless', u'author': [u'Douglas', u'Adams']}}]
>>> newJson = [{
...     "pk": 2,
...     "model": "store.book",
...     "fields": {
...         "name": "Henry",
...         "author": ["Hans"]
...     }
... }]
>>> jsonFromFile.append(newJson[0])
>>> jsonFromFile
[{u'pk': 1, u'model': u'store.book', u'fields': {u'name': u'Mostly Harmless', u'author': [u'Douglas', u'Adams']}}, {'pk': 2, 'model': 'store.book', 'fields': {'name': 'Henry', 'author': ['Hans']}}]
>>> json.dump(jsonFromFile, fileLoop)
>>> fileLoop.close()

【讨论】:

  • 这意味着在内存中加载千兆字节,我不想这样做
  • 在这种情况下,我认为@Till Hoffmann 的回答会更合适,因为您不会将其读入内存。
  • 在你的问题中也包括内存限制。
  • 是的,但是会再次在内存中,我不想打开文件来读取它,他是在内存中加载的
  • 不,文件没有读入内存。请注意,打开文件和读取文件是两个不同的操作。 open 只返回文件的句柄。只有调用read时才会将数据读入内存。
【解决方案2】:

您不需要解析 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()

【讨论】:

  • 恐怕它会在内存中保留大量数据。我编辑我的问题
【解决方案3】:

为避免创建数 GB 的对象,您可以将每个对象存储在单独的行上。它要求您在没有用于格式化的换行符的情况下转储每个对象(json 字符串本身可能像往常一样使用\n(两个字符)):

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")

【讨论】:

    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2019-12-25
    • 2022-01-08
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    相关资源
    最近更新 更多