python 處理 json

Description

現在很常用 json 當成儲存資料的格式, 用 java 的話需要導入 library.
python 則是內建 json 的 module, 只要操作原生的資料結構就行了. 很方便.

Reference

Codes

>>> import json
>>> m = {'a':1,'b':[1,2,3,4,5,6]}
>>> with open('d:/test.txt','w') as f:
        json.dump(m,f)

        
>>> with open('d:/test.txt') as f:
        f.readline()

        
'{"a": 1, "b": [1, 2, 3, 4, 5, 6]}'
>>> with open('d:/test.txt') as f:
        x = json.load(f)

        
>>> x
{'a': 1, 'b': [1, 2, 3, 4, 5, 6]}
>>> 

File content

{"a": 1, "b": [1, 2, 3, 4, 5, 6]}

沒有留言:

張貼留言

caffeinate – make your Mac awake

When running long tests on macOS, the machine may go to sleep if you don’t touch it. There’s a built-in command that keeps it awake. ...