python json pretty
时间: 2023-07-06 20:37:33 浏览: 54
如果你想要以漂亮的格式打印 JSON 数据,可以使用 `json.dumps()` 函数的 `indent` 参数。例如:
```python
import json
data = {"name": "John", "age": 30, "city": "New York"}
pretty_data = json.dumps(data, indent=4)
print(pretty_data)
```
输出:
```
{
"name": "John",
"age": 30,
"city": "New York"
}
```
相关问题
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).
python中字典转换成json
在Python中,你可以使用`json`模块将字典转换为JSON格式的字符串。下面是一个简单的示例:
```python
import json
# 假设我们有一个字典
dict_data = {
"name": "John",
"age": 30,
"city": "New York"
}
# 使用json.dumps()函数将字典转换为JSON
json_string = json.dumps(dict_data)
print(json_string) # 输出:{"name": "John", "age": 30, "city": "New York"}
# 如果你想以更易读的方式缩进,可以设置indent参数
json_pretty = json.dumps(dict_data, indent=4)
print(json_pretty)
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)