#!/usr/bin/python
"""
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str | string |
+-------------------+---------------+
| int, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
"""
"""
[ 开头的是数组
{ 开头的对象
"""
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
meterdata = [ { 'a' : 'sdf', 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 }, {'xx': 'x1'}]
# meterdata = [{ 'meter' : 123, 'ID' : 12345 } ]
# sort_keys = True: 分行显示
# Serialize obj to a JSON formatted str using this conversion table.
# json = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
meterjson = json.dumps(meterdata, sort_keys=True, indent=4, separators=(',', ': '))
print(meterjson)
# jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
# text = json.loads(jsonData)
# print(text)
with open("test0.json", "w", encoding='utf-8') as f:
# indent 超级好用,格式化保存字典,默认为None,小于0为零个空格
# f.write(json.dumps(a, indent=4))
# f.write(json)
f.write(meterjson)
# json.dump(a,f,indent=4) # 和上面的效果一样
with open("test0.json", "r", encoding='utf-8') as f:
a0 = json.load(f) # 与 json.loads(f.read())
print('---------------------------------------------------- a0')
print(a0)
print(a0[0])
print("a0[0]['b'] is ", a0[0]['b'])
print("a0[1]['xx'] is ", a0[1]['xx'])
with open("test1.json", "r", encoding='utf-8') as f:
# print(f.read())
# aa = json.loads(f.read())
f.seek(0)
bb = json.load(f) # 与 json.loads(f.read())
print('---------------------------------------------------- bb')
# print(aa)
print(bb)
# print(bb[0]['a'])
# print(bb[0]['b'])
# print(bb[0]['c']*9)
print (bb['arrow-body-style'])
print (bb['arrow-body-style'][0])
print('---------------------------------------------------- bb for loop')
for x in bb:
print(x, bb[x])
print('---------------------------------------------------- change key value')
bb['a'] = "sdf_2new"
with open("test2.json", "w", encoding='utf-8') as f:
f.write(json.dumps(bb, sort_keys=True, indent=4, separators=(',', ': ')))