【问题标题】:Read and write a valid Json file output in Python在 Python 中读取和写入有效的 Json 文件输出
【发布时间】:2019-01-16 11:58:29
【问题描述】:
import json
import os
import shutil
import time
# import objectpath
import sys
import datetime
true = "true"
false = "false"
null = "null"

from datetime import datetime, timedelta


with open('./notificationsManagement/notifications.json') as json_file:
    data = json.load(json_file)


day_start = 30
for tuple in data:
    tuple['creationTime'] -=  int(timedelta(days = day_start).total_seconds())
    day_start -= 2

print(data)

text_file = open("output.json", "w")
text_file.write(str(data))
text_file.close()

我写了一个脚本是为了:

  1. 读取 Json 文件
  2. 执行修改
  3. 打印数据
  4. 将新的有效 Json 文件输出为“output.json”

请教了几个问题:

  1. Json 的元组有问题
  2. 数据在每个标题前打印一个“u”
  3. 新文件包含相同的“u”(主要问题)

有什么建议吗?

【问题讨论】:

标签: python json


【解决方案1】:

关于u'foo'

这是正常的 Python 行为,u'something' 表示您的字符串是 Unicode 字符串。 see more about Unicode strings here

您可以通过使用此行将您的 dict 写入 JSON 字符串来修复它,顺便说一句,您应该始终使用 json.dump()(或 json.dumps())来写入 JSON 字符串:

text_file.write(json.dump(data))

关于按键顺序

首先,JSON's RFC 明确说明了这一点:

对象是零个或多个名称/值的无序集合 对,其中名称是字符串,值是字符串、数字、 布尔值、空值、对象或数组。

这里,“object”的意思是“hash”,这就是我们在 Python 中所说的“dictionnaries”。这意味着 JSON 字符串的键是从不有序的。

此外,

data = json.load(json_file) 加载一个 JSON 字符串并将其解析为 Python 字典。 Python dicts 也没有排序(至少在 Python3.7 之前)。

这意味着两件事:

  1. 您无法按预期顺序读取 JSON 文件。
  2. 根据第 1 点,按特定顺序写入 JSON 字符串是没有意义的(因为您将无法按相同顺序读取它)

【讨论】:

    【解决方案2】:

    关于问题 2 和 3。

    您应该在没有 Unicode 输出的情况下将其打印出来。

    在此处参考编写 JSON 文件。

    How do I write JSON data to a file?

    关于问题3:

    如果您想订购成为保护者,您应该使用OrderedDict

    How to preserve ordering of items in a python dictionary?

    【讨论】:

      【解决方案3】:

      你确定这真的在运行吗? (清除所有 .pyc)

      数据是一个字典,你遍历键(字符串)并将它们视为字典

      for tuple in data:
          tuple['creationTime'] -=  int(timedelta(days = day_start).total_seconds())
      

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2012-11-12
        • 1970-01-01
        • 2020-05-13
        相关资源
        最近更新 更多