简体   繁体   English

Python - 转换多行 json

[英]Python - Convert multiline json

I am trying to convert multiline json to single line json.我正在尝试将多行 json 转换为单行 json。 So the existing json file I have looks like this.所以我现有的 json 文件看起来像这样。 When I load the file, it comes in a dictionary and not sure how to strip blank spaces in the dictionary.当我加载文件时,它出现在字典中,不知道如何去除字典中的空格。

 f = open(test.json')
 data = json.load(f)

My json look like我的 json 看起来像

 {
   "a": [
   "b",
   "bill",
   "clown",
   "circus"
],
    "vers": 1.0
}

What I would like it to come out is the following.我希望它出来的是以下内容。

{"a":["b","bill","clown","circus"],"vers":1}

Any help on this would be greatly appreciated.对此的任何帮助将不胜感激。 Thanks!谢谢!

You can use this library and read documents:您可以使用此库并阅读文档:

https://pypi.org/project/JSON_minify/ https://pypi.org/project/JSON_minify/

Using the standard library json you can get:使用标准库json您可以获得:

import json

with open('test.json') as handle:
    data = json.load(handle)

text = json.dumps(data, separators=(',', ':'))
print(text)

Result:结果:

{"a":["b","bill","clown","circus"],"vers":1.0}

Remark:评论:

  • 1.0 is not simplified to 1 , probably, because this would change the type from float to int at Python level. 1.0未简化为1 ,可能是因为这会在 Python 级别将类型从float更改为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM