# Python Dict物件與JSON類型轉換
###### tags: `json` `dict` `python`
[ToC]
## :memo: 語法
### :rocket: 將json string轉成python dict
json.loads():將json轉成python dict
```python=
import json
# 由字串變數轉dict
jsonstr = '{"Id": 1, "Name": "John", "Email": "John@example.com"}'
jsondict1 = json.loads(jsonstr)
#由json檔案轉dict
with open('data.json', "r", encoding = "utf8") as file:
jsondict2 = json.load(file)
print(jsondict1)
print(type(jsondict1))
print(jsondict1)
print(type(jsondict2))
-------------------------------
{'Id': 1, 'Name': 'John', 'Email': 'John@example.com'}
<class 'dict'>
{'Id': 2, 'Name': 'Mary', 'Email': 'Mary@example.com'}
<class 'dict'>
```
### :rocket: 從python dict轉換為json string
json.dumps():從python dict轉換為json
```python=
import json
json_dict = {'id': 1, 'Name': 'John', 'Email': 'John@example.com'}
json_str = json.dumps(json_dict) # dict 轉成 string
with open("sample.json", "w", encoding = "utf8") as outfile:
outfile.write(json_str) # 將 string 存成 json檔
print(json_dict)
print(type(json_dict))
print(json_str)
print(type(json_str))
-------------------------------
{'id': 1, 'Name': 'John', 'Email': 'John@example.com'}
<class 'dict'>
{"id": 1, "Name": "John", "Email": "John@example.com"}
<class 'str'>
```
## :memo: Title
### :rocket: Sub-Title
1. list1
2. list2
```
code area
```
Author - [name=林奇賢]