Python字符串和json类型的相互转换实例演示,python字符串转json、json转字符串

简介: Python字符串和json类型的相互转换实例演示,python字符串转json、json转字符串

     

首先进行是字符串转换 json 的实例,用的 json.loads() 方法。

需要注意的是: 如果字符串里包含 \ 符号,转换会报错。

# -*- coding: UTF8 -*-
import json
# 字符串跨行用\连接,注意\后面不要有空格
s = '{' \
    '"file_path":"/data/oracle_bak/auto_2105_oracle_yz0515.dmp",' \
    '"schema_name1":"auto_2105_oracle_yz",' \
    '"schema_name2":"auto_2105_ora19c_yz",' \
    '"password":"1",' \
    '"odbc":"orcl"' \
    '}'
# 字符串转化为json
s_json = json.loads(s)
print("转化后遍历json文件:")
# 遍历json
for key, value in s_json.items():
    print(key + " : " + value)

image.png

然后是 json 转换字符串的实例,用的 json.dumps() 方法。

# -*- coding: UTF8 -*-
import json
s_json = {
    "file_path":"/data/oracle_bak/auto_2105_oracle_yz0515.dmp",
    "schema_name1":"auto_2105_oracle_yz",
    "schema_name2":"auto_2105_ora19c_yz",
    "password":"1",
    "odbc":"orcl"
    }
# json转化为字符串
s = json.dumps(s_json)
print("转化后的字符串为:\n" + s)

image.png

喜欢的点个赞❤吧!

   

目录
相关文章
|
1月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
137 1
|
1月前
|
JSON 算法 API
Python采集淘宝商品评论API接口及JSON数据返回全程指南
Python采集淘宝商品评论API接口及JSON数据返回全程指南
|
1月前
|
JSON API 数据安全/隐私保护
Python采集淘宝拍立淘按图搜索API接口及JSON数据返回全流程指南
通过以上流程,可实现淘宝拍立淘按图搜索的完整调用链路,并获取结构化的JSON商品数据,支撑电商比价、智能推荐等业务场景。
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
292 100
|
2月前
|
IDE 开发工具 开发者
Python类型注解:提升代码可读性与健壮性
Python类型注解:提升代码可读性与健壮性
253 102
|
2月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
402 99
|
2月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
2月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
2月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
2月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化

热门文章

最新文章

推荐镜像

更多