JSON转储自定义格式 [英] JSON dumps custom formatting

查看:218
本文介绍了JSON转储自定义格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Python字典转储成具有特定自定义格式的JSON文件。例如,以下字典 my_dict

 'text_lines':[ {line1},{line2}] 

转储与

  f.write(json.dumps(my_dict,sort_keys = True,indent = 2))

看起来像这样

 text_lines:[
{
line1
},
{
line2
}
]
pre>

而我更喜欢这样

 text_lines :
[
{line1},
{line2}
]

同样,我想要以下

 location:[
22 ,
-8
]

看起来像这样

 位置:[22,-8] 

(也就是说,更像一个坐标,它是)。



我知道这是一个化妆品e,但是保存这个格式很容易手动编辑文件是很重要的。



做这种定制的任何方式?一个解释的例子会很好(文档没有让我很远)。

解决方案

你将需要创建一个子类json.JSONEncoder类,并为每种类型的值覆盖方法
,以便他们编写所需的格式。您可能会最终重新实施
,具体取决于您的格式需求。



http://docs.python.org/2/library/json.html 有一个扩展
JSONEncoder的例子。


I'd like to dump a Python dictionary into a JSON file with a particular custom format. For example, the following dictionary my_dict,

'text_lines': [{"line1"}, {"line2"}]

dumped with

f.write(json.dumps(my_dict, sort_keys=True, indent=2))

looks like this

  "text_lines": [
    {
      "line1"
    }, 
    {
      "line2"
    }
  ]

while I prefer that it looks like this

  "text_lines": 
  [
    {"line1"}, 
    {"line2"}
  ]

Similarly, I want the following

  "location": [
    22, 
    -8
  ]

to look like this

  "location": [22, -8]

(that is, more like a coordinate, which it is).

I know that this is a cosmetic issue, but it's important to me to preserve this formatting for easier hand editing of the file.

Any way of doing this kind of customisation? An explained example would be great (the docs did not get me very far).

解决方案

You will need to create a subclass of the json.JSONEncoder class and override the methods for each type of value so they write the format you need. You may end up re-implementing most of them, depending on what your formatting needs are.

http://docs.python.org/2/library/json.html has an example for extending the JSONEncoder.

这篇关于JSON转储自定义格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆