본문 바로가기

데이터 분석/Flask

JSON (JavaScript Object Notation)

728x90

JSON은

1) 온라인 API에서 데이터를 가져올때 가장 많이 사용됩니다.

2) 구성파일 및 다른 종류의 데이터를 다룰때도 사용됩니다.

3) javascript의 영향(개체 표기법)을 받았지만 독립적인(다른) 언어입니다.

1. python에서 json의 Type입니다.

import json

people_string = """
{
    "people" : [
        {
            "name": "Molecule Man",
            "age": 29,
            "secretIdentity": null,
            "has_license" : true,
            "powers": [
            "Radiation resistance",
            "Turning tiny",
            "Radiation blast"
            ]
        },
        {
            "name": "Madame Uppercut",
            "age": 39,
            "secretIdentity": "Jane Wilson",
            "has_license" : false,
            "powers": [
            "Million tonne punch",
            "Damage resistance",
            "Superhuman reflexes"
            ]
        }
        ]
}
"""

data = json.loads(people_string)

print(data)
print(type(data));
print(type(data['people']));

위 코드를 실행하면 아래와 같은 결과가 나옵니다.

{'people': [
{'name': 'Molecule Man', 'age': 29, 'secretIdentity': None, 'has_license': True, 
'powers': ['Radiation resistance', 'Turning tiny', 'Radiation blast']}, 
{'name': 'Madame Uppercut', 'age': 39, 'secretIdentity': 'Jane Wilson', 'has_license': False, 
'powers': ['Million tonne punch', 'Damage resistance', 'Superhuman reflexes']}
]}
<class 'dict'>
<class 'list'>

json 객체의 타입은 딕셔너리, 객체 속의 array는 list, null은 none로 아래의 표와 같이 변환됩니다.

예시

딕셔너리로 변환됐기 때문에, 키값으로 엑세스할 수 있습니다.

data = json.loads(people_string)

for person in data['people']:
    print(person)
    
# 결과
{'name': 'Molecule Man', 'age': 29, 'secretIdentity': None, 'has_license': True, 'powers': ['Radiation resistance', 'Turning tiny', 'Radiation blast']}
{'name': 'Madame Uppercut', 'age': 39, 'secretIdentity': 'Jane Wilson', 'has_license': False, 'powers': ['Million tonne punch', 'Damage resistance', 'Superhuman reflexes']}

people 개체의 목록에도 각각의 이름이 있는데, 이 이름으로도 호출이 가능합니다.

 

data = json.loads(people_string)

for person in data['people']:
    print(person['name'])
    
# 결과
Molecule Man
Madame Uppercut

json 데이터는 수정도 가능합니다.

data = json.loads(people_string)

for person in data['people']:
    del person['secretIdentity']

new_string = json.dumps(data)

print(new_string)

{"people": [{"name": "Molecule Man", "age": 29, "has_license": true, "powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]}, {"name": "Madame Uppercut", "age": 39, "has_license": false, "powers": ["Million tonne punch", "Damage resistance", "Superhuman reflexes"]}]}

indent 는 들여쓰기를 말하고, sort_keys는 알파벳순으로 정렬해줍니다.

data = json.loads(people_string)

for person in data['people']:
    del person['secretIdentity']

new_string = json.dumps(data, indent=2, sort_keys=True)

print(new_string)

# 결과
{
  "people": [
    {
      "age": 29,
      "has_license": true,
      "name": "Molecule Man",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "age": 39,
      "has_license": false,
      "name": "Madame Uppercut",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    }
  ]
}

states.json이라는 파일을 이 링크에서 받아서 같은 디렉토리에 넣어준 후 아래의 코드를 실행하면

import json


with open('states.json') as f:
# 위 코드는 f = open('test.txt') 와 비슷하지만 with문은 블록내에서만 파일을 열고닫습니다
    data = json.load(f)

for state in data['states']:
    print(state['name'], state['abbreviation'])

 아래와 같은 결과가 나옵니다

Alabama AL
Alaska AK
Arizona AZ
Arkansas AR
California CA
Colorado CO
Connecticut CT
Delaware DE
Florida FL

dump함수를 통해 파일을 새로 생성할 수 도 있습니다.

import json

with open('states.json') as f:
# 위 코드는 f = open('test.txt') 와 비슷하지만 with문은 블록내에서만 파일을 열고닫습니다
    data = json.load(f)

for state in data['states']:
    del state['area_codes']

with open('new_states.json', 'w') as f:
    json.dump(data, f, indent=2)
{
  "states": [
    {
      "name": "Alabama",
      "abbreviation": "AL"
    },
    {
      "name": "Alaska",
      "abbreviation": "AK"
    },
    {
      "name": "Arizona",
      "abbreviation": "AZ"
    },

 

위에서 확인했듯이 dump() 와 dumps()의 차이는

 

json.dumps() 메소드는 Python 객체를 JSON 문자열로 변환 할 수 있습니다. (json 형태로 만들어준다.)

구문 : json.dumps (dict, indent)

매개 변수 :

  • dictionary – JSON 객체로 변환해야하는 사전의 이름입니다.
  • 들여 쓰기 – 들여 쓰기 단위 수를 정의합니다.

json.dump() 메소드는 JSON 파일에 쓰는 데 사용할 수 있습니다. (json 파일로 만들어준다.)

구문 : json.dump (dict, file_pointer)

매개 변수 :

  • dictionary – JSON 객체로 변환해야하는 사전의 이름입니다.
  • 파일 포인터 – 쓰기 또는 추가 모드에서 열린 파일의 포인터 .

'데이터 분석 > Flask' 카테고리의 다른 글

Flask - 패키지 구조화  (0) 2021.03.27
Flask - SQLAlchemy(ORM)  (0) 2021.03.27
HTTP  (0) 2021.03.26
Flask - 2. Forms and User Input  (0) 2021.03.25
Flask - 1. 기본설정, 템플릿, 부트스트랩  (0) 2021.03.23