# https://docs.python.org/3/library/json.html?highlight=json#module-json


# json → dict
>>> import json
>>> import urllib.request
>>> _response = urllib.request.urlopen("http://lotto.kaisyu.com/api?method=get")    # returns json
>>> print(_response.read())
b'{"bnum": 24, "gno": 876, "gdate": "2019-09-14", "nums": [5, 16, 21, 26, 34, 42]}'
>>> 
>>> _response = urllib.request.urlopen("http://lotto.kaisyu.com/api?method=get")
>>> _dict = json.loads(_response.read())
>>> type(_dict)
<class 'dict'>
>>>
>>> print(_dict)
{'bnum': 24, 'gno': 876, 'gdate': '2019-09-14', 'nums': [5, 16, 21, 26, 34, 42]}
>>>
>>> _dict["nums"]
[5, 16, 21, 26, 34, 42]



# dict → json
>>> js = json.dumps(_dict, indent=4)
>>> type(js)
<class 'str'>
>>> print(js)
{
    "bnum": 24,
    "gno": 876,
    "gdate": "2019-09-14",
    "nums": [
        5,
        16,
        21,
        26,
        34,
        42
    ]
}


# dict string → dict
>>> import ast
>>> _response = urllib.request.urlopen("http://lotto.kaisyu.com/api?method=get&type=python")    # returns string of dictionary type
>>> print(_response.read())
b"{'bnum': 24, 'gno': 876, 'gdate': '2019-09-14', 'nums': [5, 16, 21, 26, 34, 42]}"
>>> 
>>> _response = urllib.request.urlopen("http://lotto.kaisyu.com/api?method=get&type=python")
>>> _dict = ast.literal_eval(_response.read().decode())
>>> type(_dict)
<class 'dict'>
>>> 
>>> print(_dict)
{'bnum': 24, 'gno': 876, 'gdate': '2019-09-14', 'nums': [5, 16, 21, 26, 34, 42]}
>>> 
>>> _dict["nums"]
[5, 16, 21, 26, 34, 42]












>>> _dic = {"A":1, "B":2, "C":3, "D":4}
>>> type(_dic)
<class 'dict'>

# dic -> json
>>> _json = json.dumps(_dic)
>>> type(_json)
<class 'str'>
>>> _json
'{"A": 1, "B": 2, "C": 3, "D": 4}'

# json -> dic
>>> _dic = json.loads(_json)
>>> type(_dic)
<class 'dict'>
>>> _dic
{'A': 1, 'B': 2, 'C': 3, 'D': 4}
>>> 

# dic -> json
>>> _json = json.JSONEncoder().encode(_dic)
>>> type(_json)
<class 'str'>
>>> _json
'{"A": 1, "B": 2, "C": 3, "D": 4}'

# json -> dic
>>> _dic = json.JSONDecoder().decode(_json)
>>> type(_dic)
<class 'dict'>
>>> _dic
{'A': 1, 'B': 2, 'C': 3, 'D': 4}