码迷,mamicode.com
首页 > 编程语言 > 详细

Python——数据存储:JSON操作

时间:2018-10-31 12:37:23      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:使用   type   XML   pytho   .json   李宁   括号   回调   port   

  JSON格式的数据格式广泛使用在各种应用中,比XML格式更轻量级,所以现在很多应用都选择JSON格式保存数据,尤其是需要通过网络传输(如socket传输)数据时,这对于移动应用更具有优势。JSON格式数据比XML格式的数据量更小,所以传输速度更快,也更节省数据流量(省钱),因此,在移动APP应用中,几乎都是采用了JSON格式。

  JSON格式的数据可以保存数组和对象。JSON数组用一对中括号‘[  ]‘将数据括起来;JSON对象用一对大括号‘{  }‘将数据括起来。本文介绍JSON字符串与字典的互相转换、JSON字符串与类实例互转、JSON与XML互转等知识点。

一、JSON字符串与字典互转实例

import json

#定义一个字典
datadict = {
‘name‘:‘Bill‘,
‘company‘:‘Microsoft‘,
‘age‘:34
}
#定义一个列表
datalist =[20,‘names‘,
{‘name‘:‘Bill‘,‘age‘:30,‘salary‘:2000},
{‘name‘:‘Chen‘,‘age‘:40,‘salary‘:3000},
{‘name‘:‘Ling‘,‘age‘:50,‘salary‘:4000}
]

# 将字典转换为json字符串
jsonstr1 = json.dumps(datadict)
print(jsonstr1)
print(‘-----------------------‘)
#输出:{"company": "Microsoft", "name": "Bill", "age": 34}
# 将列表转换为json字符串
jsonstr2 = json.dumps(datalist)
print(jsonstr2) #输出:{"company": "Microsoft", "name": "Bill", "age": 34}
print(‘-----------------------‘)
#输出:
[20, "names", {"age": 30, "name": "Bill", "salary": 2000}, {"age": 40, "name": "Chen", "salary": 3000}, {"age": 50, "name": "Ling", "salary": 4000}]

# 将JSON字符串转成字典
data = json.loads(jsonstr1)
print(type(data))
print(data)
# 输出字典:{‘company‘: ‘Microsoft‘, ‘name‘: ‘Bill‘, ‘age‘: 34}
# 将JSON字符串转成列表
data = json.loads(jsonstr2)
print(type(data))
print(data)

二、JSON字符串与类实例互转
(一)
Json串转为类实例
# 1、用类实例
class Product:
def __init__(self, d):
self.__dict__ = d

# f = open(‘./files/product.json‘,‘r‘)
# jsonstr = f.read()

jsonstr = ‘‘‘
{"name":"iPhone9",
"price":9999,
"count":3000
}
      ‘‘‘
my1 = json.loads(jsonstr,object_hook=Product)
print(my1.__dict__)
print(‘name={}‘.format(my1.name))
print(‘price={}‘.format(my1.price))
print(‘count={}‘.format(my1.count))
print(‘------------------------------‘)

# 2、用回调函数
def jsontoProduct(d):
return Product(d)

my2 = json.loads(jsonstr,object_hook=jsontoProduct)
print(my2.__dict__)
print(‘name={}‘.format(my2.name))
print(‘price={}‘.format(my2.price))
print(‘count={}‘.format(my2.count))

# f.close()

# 输出:
‘‘‘

{‘count‘: 3000, ‘price‘: 9999, ‘name‘: ‘iPhone9‘}
name=iPhone9
price=9999
count=3000
------------------------------
{‘count‘: 3000, ‘price‘: 9999, ‘name‘: ‘iPhone9‘}
name=iPhone9
price=9999
count=3000

‘‘‘

 

(二)类实例转成JSON串

class Product:
def __init__(self,name,price,count):
self.name = name
self.price = price
self.count = count

def producttoDict(obj):
return {
‘name‘:obj.name,
‘price‘:obj.price,
‘count‘:obj.count
}
product = Product(‘特斯拉‘,30000000,10)
jsonstr = json.dumps(product,default=producttoDict,ensure_ascii=False)
print(jsonstr)
#输出:{"name": "特斯拉", "count": 10, "price": 30000000}

(三)
类实例列表与JSON串互转
# f = open(‘./files/products.json‘,‘r‘,encoding=‘utf-8‘)
# jsonstr = f.read()
jsonstr = ‘‘‘
[
{
"name":"iPhone9",
"price":9999.9,
"count":2000
},
{
"name":"特斯拉",
"price":1000000,
"count":123
}
]
‘‘‘

class Product:
def __init__(self, d):
self.__dict__ = d
products = json.loads(jsonstr,object_hook=Product)

for p in products:
print(‘name={}‘.format(p.name))
print(‘price={}‘.format(p.price))
print(‘count={}‘.format(p.count))
print(‘====================‘)
# f.close()

def producttoDict(product):
return {
‘name‘:product.name,
‘price‘:product.price,
‘count‘:product.count
}
jsonstr2 = json.dumps(products,default=producttoDict,ensure_ascii=False)
print(jsonstr2)
# 输出:
‘‘‘

name=iPhone9
price=9999.9
count=2000
====================
name=特斯拉
price=1000000
count=123
====================
[{"price": 9999.9, "name": "iPhone9", "count": 2000}, {"price": 1000000, "name": "特斯拉", "count": 123}]

‘‘‘

三、JSON格式与XML格式互转

import json
import dicttoxml
import xmltodict

# f=open(‘./files/products.json‘,‘r‘,encoding=‘utf-8‘)
# jsonstr = f.read()
jsonstr = ‘‘‘
[
{
"name":"iPhone9",
"price":9999.9,
"count":2000
},
{
"name":"特斯拉",
"price":1000000,
"count":123
}
]
‘‘‘
dicts = json.loads(jsonstr)
# f.close()
print(‘1、------------------------‘)
print(dicts)
print(‘2、------------------------‘)
xmlstr = dicttoxml.dicttoxml(dicts).decode(‘utf-8‘)
print(xmlstr)
print(‘3、-------------------------‘)

dict2 = xmltodict.parse(xmlstr) #字典
jsonstr2 = json.dumps(dict2)
print(jsonstr2)
dict3 = json.loads(jsonstr2)
print(type(dict3))
print(dict3)
for li in dict3[‘root‘][‘item‘]:
print(li[‘name‘][‘#text‘])
print(li[‘price‘][‘#text‘])
print(li[‘count‘][‘#text‘])
print(‘-----------------‘)

# 输出:
‘‘‘

1、------------------------

[{‘count‘: 2000, ‘price‘: 9999.9, ‘name‘: ‘iPhone9‘}, {‘count‘: 123, ‘price‘: 1000000, ‘name‘: ‘特斯拉‘}]
2、------------------------
<?xml version="1.0" encoding="UTF-8" ?><root><item type="dict"><count type="int">2000</count><price type="float">9999.9</price><name type="str">iPhone9</name></item><item type="dict"><count type="int">123</count><price type="int">1000000</price><name type="str">特斯拉</name></item></root>
3、-------------------------
{"root": {"item": [{"@type": "dict", "count": {"@type": "int", "#text": "2000"}, "price": {"@type": "float", "#text": "9999.9"}, "name": {"@type": "str", "#text": "iPhone9"}}, {"@type": "dict", "count": {"@type": "int", "#text": "123"}, "price": {"@type": "int", "#text": "1000000"}, "name": {"@type": "str", "#text": "\u7279\u65af\u62c9"}}]}}
<class ‘dict‘>
{‘root‘: {‘item‘: [{‘@type‘: ‘dict‘, ‘price‘: {‘@type‘: ‘float‘, ‘#text‘: ‘9999.9‘}, ‘name‘: {‘@type‘: ‘str‘, ‘#text‘: ‘iPhone9‘}, ‘count‘: {‘@type‘: ‘int‘, ‘#text‘: ‘2000‘}}, {‘@type‘: ‘dict‘, ‘price‘: {‘@type‘: ‘int‘, ‘#text‘: ‘1000000‘}, ‘name‘: {‘@type‘: ‘str‘, ‘#text‘: ‘特斯拉‘}, ‘count‘: {‘@type‘: ‘int‘, ‘#text‘: ‘123‘}}]}}
iPhone9
9999.9
2000
-----------------
特斯拉
1000000
123
-----------------

‘‘‘

参考文献:
1、《python从菜鸟到高手》,作者:李宁
 

Python——数据存储:JSON操作

标签:使用   type   XML   pytho   .json   李宁   括号   回调   port   

原文地址:https://www.cnblogs.com/chenhaiming/p/9882205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!