๐Ÿ“‚์›น ๊ฐœ๋ฐœ(Web)/๐ŸํŒŒ์ด์ฌ(Python)

ํŒŒ์ด์ฌ json

๐Ÿ‘ฉ‍๐ŸŽ“์ธํ…”๋ฆฌ๊ฐ์ž๐Ÿฅ” 2023. 2. 8. 17:28
JSON (JavaScript Object Notation)
    -๋”•์…”๋„ˆ๋ฆฌ ๋น„์Šทํ•˜๋‹ค
    -๊ตฌ์กฐ { K : V }

1. Json Writer

# ์ฒซ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•

dict_list = [
    {
        'name' : 'james',
        'age':20,
        'spec':[
            175.5,
            70.5
        ]
    },
    {
        'name':'alice',
        'age':21,
        'spec': [
            168.5,
            60.5
        ]
    }
]
json_string = json.dumps(dict_list)

with open('dictlist.json', 'w') as file:
    file.write(json_string)
print('dictlist.json ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.')

# ๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•

import json

dict_list = [
    {
        'name' : 'james',
        'age':20,
        'spec':[
            175.5,
            70.5
        ]
    },
    {
        'name':'ํ™๊ธธ๋™',
        'age':21,
        'spec': [
            168.5,
            60.5
        ]
    }
]
# indent ๋“ค์—ฌ์“ฐ๊ธฐ, ensure_ascii=False ํ•œ๊ธ€์ฝ๊ธฐ
json_string = json.dumps(dict_list, indent=4, ensure_ascii=False)
with open('dictlist.json', 'w', encoding='UTF-8') as file:
    file.write(json_string)
print('dictlist.json ํŒŒ์ผ์ด ์ƒ์„ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.')

 

2. Json Reader

import json

with open('dictList.json', 'r', encoding='UTF-8') as file:
    json_reader = file.read()
    dict_list = json.loads(json_reader)

for dic in dict_list:
    print('์ด๋ฆ„: {}'.format(dic['name']))
    print('๋‚˜์ด: {}'.format(dic['age']))
    print('ํ‚ค: {}'.format(dic['spec'][0]))
    print('๋ชธ๋ฌด๊ฒŒ: {}'.format(dic['spec'][1]))
    print()