python - 将键的字典和键内的字典列表保存到 JSON,其中字典按行存储

标签 python json python-3.x dictionary

我有一个类似的问题this previous question 。但是,我的字典具有如下结构

data_dict = {
  'refresh_count': 1,
  'fetch_date': '10-10-2019',
  'modified_date': '',
  'data': [
      {'date': '10-10-2019', 'title': 'Hello1'}, 
      {'date': '11-10-2019', 'title': 'Hello2'}
  ]
}

我想将其存储在 JSON 中,以便我的数据仍然存储在每行一个字典中。像这样的东西:

{
  'refresh_count': 1,
  'fetch_date': '10-10-2019',
  'modified_date': '',
  'data': [
      {'date': '10-10-2019', 'title': 'Hello1'}, 
      {'date': '11-10-2019', 'title': 'Hello2'}
  ]
}

我无法仅使用 json.dumps (或 dump)或以前的解决方案来实现它。

json.dumps(data_dict, indent=2)

>> {
  "refresh_count": 1,
  "fetch_date": "10-10-2019",
  "modified_date": "",
  "data": [
    {
      "date": "10-10-2019",
      "title": "Hello1"
    },
    {
      "date": "11-10-2019",
      "title": "Hello2"
    }
  ]

}

最佳答案

这确实是一个 hack,但是您可以实现一个自定义 JSON 编码器来执行您想要的操作(请参阅 Custom JSON Encoder in Python With Precomputed Literal JSON )。对于任何您不想缩进的对象,请用 NoIndent 将其包裹起来。类(class)。自定义 JSON 编码器将在 default() 中查找此类型。方法并返回唯一字符串 ( __N__ ) 并将未缩进的 JSON 存储在 self._literal 中。随后,在调用encode()时,这些唯一的字符串将被替换为不缩进的 JSON。

请注意,您需要选择不可能出现在编码数据中的字符串格式,以避免无意中替换某些内容。

import json


class NoIndent:

    def __init__(self, o):
        self.o = o


class MyEncoder(json.JSONEncoder):

    def __init__(self, *args, **kwargs):
        super(MyEncoder, self).__init__(*args, **kwargs)
        self._literal = []

    def default(self, o):
        if isinstance(o, NoIndent):
            i = len(self._literal)
            self._literal.append(json.dumps(o.o))
            return '__%d__' % i
        else:
            return super(MyEncoder, self).default(o)

    def encode(self, o):
        s = super(MyEncoder, self).encode(o)
        for i, literal in enumerate(self._literal):
            s = s.replace('"__%d__"' % i, literal)
        return s


data_dict = {
  'refresh_count': 1,
  'fetch_date': '10-10-2019',
  'modified_date': '',
  'data': [
      NoIndent({'date': '10-10-2019', 'title': 'Hello1'}),
      NoIndent({'date': '11-10-2019', 'title': 'Hello2'}),
  ]
}

s = json.dumps(data_dict, indent=2, cls=MyEncoder)
print(s)

super(MyEncoder, self).encode(o) 返回的中间表示:

{
  "fetch_date": "10-10-2019", 
  "refresh_count": 1, 
  "data": [
    "__0__", 
    "__1__"
  ], 
  "modified_date": ""
}

最终输出:

{
  "fetch_date": "10-10-2019", 
  "refresh_count": 1, 
  "data": [
    {"date": "10-10-2019", "title": "Hello1"}, 
    {"date": "11-10-2019", "title": "Hello2"}
  ], 
  "modified_date": ""
}

关于python - 将键的字典和键内的字典列表保存到 JSON,其中字典按行存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58327845/

相关文章:

python - 组合两个字典,其中字典一个键是整数范围,第二个字典键是可能落入第一个键范围的整数

python - ValueError:形状 (20,1) 和 (2,1) 未对齐:1 (dim 1) != 2 (dim 0)

python-3.x - 无法将 tensorflow 模型转换为 tflite

python - 不断地读取一个文件最终会损坏我的硬盘吗?

json - 将解除嵌套列表摇至顶层

java - ListView 项目未使用 AsyncTask 加载

python - 如何将字典附加到 Pandas 数据框?

python - 如何在句子中找到与 python 中的单词相反的单词

python - 从数据库加载大数据并转换为 JSON 时如何提高性能

python - Gevent:重试一次greenlet