1. 程式人生 > >Python——資料儲存:JSON操作

Python——資料儲存:JSON操作

  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從菜鳥到高手》,作者:李寧