1. 程式人生 > >json字串互相轉換python資料型別(4 大方法!)

json字串互相轉換python資料型別(4 大方法!)

!/usr/bin/python3

-- coding: utf-8 --

import json

4 大方法

json 字串 互相轉換 python 資料型別

s 表示字串的意思

str=”“”
{
“a”:”x”,
“b”:”y”
}
“”“

loads json 字串 轉 python型別

data = json.loads(str)
print(type(data))

load 從檔案中 讀取 json字串 轉 ptyhon型別

with open(‘09-data.json’,’r’) as f:

data = json.load(f)
print(type(data))
print(data)

dumps 把 python 型別 轉成 json 字串

data = {
“xxx”:”aaa”,
“yyy”:”bbb”
}
print(type(data))
str = json.dumps(data)
print(type(str))
print(str)

dump 把 python 型別 轉成 json 字串並且寫入到檔案中

with open(‘10-data.json’,’w’,encoding=’utf-8’) as f:

json.dump(data,f)