python json pretty
时间: 2023-07-08 15:54:03 浏览: 40
在 Python 中,可以使用 json 模块中的 dumps 函数来将 Python 对象转换成 JSON 格式字符串,并使用参数 indent 来指定格式化后的缩进空格数,从而实现 JSON 美化。
示例代码如下:
```python
import json
data = {"name": "Alice", "age": 20, "hobbies": ["reading", "traveling", "swimming"]}
# 将 Python 对象转换成 JSON 格式字符串,并指定缩进空格数为 4
json_str = json.dumps(data, indent=4)
print(json_str)
```
输出结果为:
```
{
"name": "Alice",
"age": 20,
"hobbies": [
"reading",
"traveling",
"swimming"
]
}
```
相关问题
Python json
Python has built-in support for working with JSON data. The `json` module in Python can be used to parse JSON strings into Python objects, and to serialize Python objects into JSON strings.
Here's an example of parsing a JSON string into a Python object:
```python
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_string)
print(data["name"]) # Output: John
print(data["age"]) # Output: 30
print(data["city"]) # Output: New York
```
And here's an example of serializing a Python object into a JSON string:
```python
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data)
print(json_string) # Output: {"name": "John", "age": 30, "city": "New York"}
```
In addition to parsing and serializing JSON data, the `json` module also provides functions for pretty-printing JSON data and for decoding JSON data incrementally as it is received (useful for processing large JSON files).
json转xml
可以使用Python中的`xmltodict`库来将JSON转换为XML。以下是一个简单的示例:
```python
import xmltodict
import json
# 将JSON字符串转换为Python字典
json_str = '{"person": {"name": "John", "age": 30}}'
json_dict = json.loads(json_str)
# 将Python字典转换为XML字符串
xml_str = xmltodict.unparse(json_dict, pretty=True)
print(xml_str)
```
输出结果为:
```xml
<?xml version="1.0" encoding="utf-8"?>
<person>
<name>John</name>
<age>30</age>
</person>
```
注意:转换过程中可能存在一些限制和不兼容性,需要根据具体情况进行调整和处理。