json格式转string
时间: 2023-06-28 08:03:52 浏览: 52
在大多数编程语言中,将 JSON 格式转换为字符串通常是一个内置函数或方法。下面以 Python 为例:
```python
import json
# 定义 JSON 对象
person = {"name": "Alice", "age": 25, "city": "New York"}
# 将 JSON 对象转换为字符串
person_str = json.dumps(person)
# 输出字符串
print(person_str)
```
输出结果为:
```
{"name": "Alice", "age": 25, "city": "New York"}
```
如果要美化输出的字符串,可以使用 `indent` 参数,例如:
```python
import json
# 定义 JSON 对象
person = {"name": "Alice", "age": 25, "city": "New York"}
# 将 JSON 对象转换为字符串,并且美化输出
person_str = json.dumps(person, indent=4)
# 输出字符串
print(person_str)
```
输出结果为:
```
{
"name": "Alice",
"age": 25,
"city": "New York"
}
```
其他编程语言中也有类似的函数或方法来完成这个转换。
相关问题
json格式String转list
可以使用fastjson或Gson将json格式的字符串转换成list对象。
使用fastjson的方法示例:
import com.alibaba.fastjson.JSON;
import java.util.List;
String jsonString = "[{'id':1,'num':1},{'id':2,'num':2}]";
List<Goods> listStr = JSON.parseArray(jsonString, Goods.class);
使用Gson的方法示例:
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.List;
String jsonString = "[{'id':1,'num':1},{'id':2,'num':2}]";
List<Goods> listStr = new Gson().fromJson(jsonString, new TypeToken<List<Goods>>() {}.getType());
其中,Goods是自定义的pojo类,用于存储json中的数据。
把json格式转换为string格式
可以使用 JSON 库中的 `json.dumps()` 方法将 JSON 格式转换为字符串格式。下面是一个示例代码:
```python
import json
json_data = {"name": "John", "age": 30, "city": "New York"}
string_data = json.dumps(json_data)
print(string_data)
```
输出结果为:
```
{"name": "John", "age": 30, "city": "New York"}
```
在这个示例中,`json_data` 是一个包含三个键值对的字典。`json.dumps()` 方法将字典转换为 JSON 格式的字符串,并将其存储在 `string_data` 变量中。最后,我们使用 `print()` 函数输出 `string_data` 变量中的字符串。