本文实例讲述了Python中 和json格式相互转换操作。分享给大家供大家参考,具体如下:

Python中 和json格式是可以互转的,就像json格式转Python字典对象那样。

格式和json格式互转用到的 todict

安装 todict

C:\\Users\\Administrator>pip3 install todict
Collecting todict
  Downloading todict-0.11.0-py2.py3-none-any.whl
Installing collected packages: todict
Successfully installed todict-0.11.0

利用pip可以直接安装。

格式转json格式

import json
import  todict
#定义 转json的函数
def  tojson( str):
  #parse是的 解析器
   parse =  todict.parse( str)
  #json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
  #dumps()方法的ident=1,格式化json
  jsonstr = json.dumps( parse,indent=1)
  print(jsonstr)
if __name__ == \"__main__\":
    =\"\"\"     #需要转换json格式的 
<student>
  <stid>10213</stid>
  <info>
    <name>name</name>
    <sex>male</sex>
  </info>
  <course>
    <name>math</name>
    <score>90</score>
  </course>
</student>
  \"\"\"
   tojson( ) #调用转换函数

\"\"

json格式转 格式

import  todict
#json转 函数
def jsonto (jsonstr):
  # todict库的unparse()json转 
   str =  todict.unparse(jsonstr)
  print( str)
if __name__ == \"__main__\":
  json = {\'student\': {\'course\': {\'name\': \'math\', \'score\': \'90\'},
            \'info\': {\'sex\': \'male\', \'name\': \'name\'}, \'stid\': \'10213\'}}
  jsonto (json)

结果:

C:\\python35\\python.exe \"D:/自动化测用例/json to .py\"
<? version=\"1.0\" encoding=\"utf-8\"?>
<student><course><name>math</name><score>90</score></course><info><name>name</name><sex>male</sex></info><stid>10213</stid></student>

Process finished with exit code 0

PS:这里再为大家推荐几款比较实用的json与 在线工具供大家参考使用:

在线 /JSON互相转换工具:
http://tools.jb51.net/code/ json

在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat

json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat

在线格式化 /在线压缩 :
http://tools.jb51.net/code/ format

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python操作 数据技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

收藏 打印