Python JSON 객체에서 중첩된 키에 접근하는 방법

PythonBeginner
지금 연습하기

소개

Python 의 다재다능함은 정보를 저장하고 교환하는 데 널리 사용되는 형식인 JSON 데이터 작업으로 확장됩니다. JSON 구조는 Python 딕셔너리와 리스트와 유사하게 중첩된 요소를 사용하여 단순하거나 복잡할 수 있습니다. 이 튜토리얼에서는 실용적인 연습을 통해 Python 에서 중첩된 JSON 구조의 데이터에 액세스하고 추출하는 방법을 배우게 됩니다.

이 랩이 끝나면 JSON 객체를 자신 있게 탐색하고, 깊이 중첩된 키에 액세스하며, Python 애플리케이션에서 중첩된 배열로 작업할 수 있게 됩니다.

Python 에서 JSON 이해하기

JSON (JavaScript Object Notation) 은 사람이 읽기 쉽고 기계가 구문 분석할 수 있는 가벼운 데이터 교환 형식입니다. Python 에서 JSON 객체는 딕셔너리로, JSON 배열은 리스트로 표현됩니다.

JSON 데이터를 탐색하기 위해 간단한 Python 스크립트를 만들어 보겠습니다.

  1. WebIDE 를 열고 메뉴에서 "File > New File"을 클릭하여 새 파일을 만듭니다.

  2. 파일을 /home/labex/project/json_practice 디렉토리에 basic_json.py로 저장합니다.

  3. basic_json.py에 다음 코드를 추가합니다.

import json

## A simple JSON object (represented as a Python dictionary)
person = {
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com",
    "is_employed": True,
    "hobbies": ["reading", "hiking", "coding"]
}

## Convert Python dictionary to JSON string
json_string = json.dumps(person, indent=2)
print("JSON as string:")
print(json_string)
print("\n" + "-" * 50 + "\n")

## Convert JSON string back to Python dictionary
parsed_json = json.loads(json_string)
print("Python dictionary:")
print(parsed_json)
print("\n" + "-" * 50 + "\n")

## Accessing basic elements
print("Basic access examples:")
print(f"Name: {parsed_json['name']}")
print(f"Age: {parsed_json['age']}")
print(f"First hobby: {parsed_json['hobbies'][0]}")
  1. WebIDE 에서 터미널을 열고 다음을 실행하여 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 basic_json.py

다음 출력을 볼 수 있습니다.

JSON as string:
{
  "name": "John Doe",
  "age": 30,
  "email": "john.doe@example.com",
  "is_employed": true,
  "hobbies": [
    "reading",
    "hiking",
    "coding"
  ]
}

--------------------------------------------------

Python dictionary:
{'name': 'John Doe', 'age': 30, 'email': 'john.doe@example.com', 'is_employed': True, 'hobbies': ['reading', 'hiking', 'coding']}

--------------------------------------------------

Basic access examples:
Name: John Doe
Age: 30
First hobby: reading

코드 이해

  • json.dumps()는 Python 객체를 JSON 형식의 문자열로 변환합니다.
  • json.loads()는 JSON 문자열을 구문 분석하여 Python 객체로 변환합니다.
  • JSON 객체의 요소에 액세스하려면 딕셔너리 구문 (object_name['key']) 을 사용합니다.
  • JSON 배열의 요소에 액세스하려면 리스트 인덱싱 (array_name[index]) 을 사용합니다.

이 예제는 Python 에서 JSON 으로 작업하기 위한 기본 작업을 보여줍니다. 다음 단계에서는 중첩된 JSON 구조에 액세스하는 방법을 살펴보겠습니다.

중첩된 딕셔너리 키에 액세스하기

JSON 객체는 종종 중첩된 구조를 포함합니다. Python 에서는 여러 개의 대괄호 또는 딕셔너리 키를 연결하여 중첩된 데이터에 액세스할 수 있습니다.

중첩된 JSON 객체를 탐색하기 위해 새 스크립트를 만들어 보겠습니다.

  1. WebIDE 에서 새 파일을 만들고 /home/labex/project/json_practice 디렉토리에 nested_dict.py로 저장합니다.

  2. nested_dict.py에 다음 코드를 추가합니다.

import json

## JSON with nested object
user_data = {
    "name": "John Doe",
    "age": 30,
    "contact": {
        "email": "john.doe@example.com",
        "phone": "555-1234",
        "address": {
            "street": "123 Main St",
            "city": "Anytown",
            "state": "CA",
            "zip": "12345"
        }
    },
    "preferences": {
        "theme": "dark",
        "notifications": True
    }
}

## Let's prettify and print the JSON structure
print("Full JSON structure:")
print(json.dumps(user_data, indent=2))
print("\n" + "-" * 50 + "\n")

## Accessing nested elements
print("Accessing nested elements:")
print(f"Email: {user_data['contact']['email']}")
print(f"City: {user_data['contact']['address']['city']}")
print(f"Theme: {user_data['preferences']['theme']}")
print("\n" + "-" * 50 + "\n")

## Safe access with get() method
print("Safe access with get():")
## get() returns None if key doesn't exist, or a default value if specified
phone = user_data.get('contact', {}).get('phone', 'Not available')
country = user_data.get('contact', {}).get('address', {}).get('country', 'Not specified')

print(f"Phone: {phone}")
print(f"Country: {country}")  ## This key doesn't exist but won't cause an error
  1. 터미널에서 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 nested_dict.py

다음과 유사한 출력을 볼 수 있습니다.

Full JSON structure:
{
  "name": "John Doe",
  "age": 30,
  "contact": {
    "email": "john.doe@example.com",
    "phone": "555-1234",
    "address": {
      "street": "123 Main St",
      "city": "Anytown",
      "state": "CA",
      "zip": "12345"
    }
  },
  "preferences": {
    "theme": "dark",
    "notifications": true
  }
}

--------------------------------------------------

Accessing nested elements:
Email: john.doe@example.com
City: Anytown
Theme: dark

--------------------------------------------------

Safe access with get():
Phone: 555-1234
Country: Not specified

중첩 액세스 이해

중첩된 JSON 구조로 작업할 때 대괄호로 키를 연결하여 중첩된 요소에 액세스할 수 있습니다.

## Syntax for nested access
value = json_data['key1']['key2']['key3']

그러나 이 접근 방식은 체인에 있는 키가 존재하지 않는 경우 오류를 발생시킬 수 있습니다. 더 안전한 방법은 get() 함수를 사용하는 것입니다. 이 함수를 사용하면 키가 누락된 경우 기본값을 제공할 수 있습니다.

## Safe access with get() method
value = json_data.get('key1', {}).get('key2', {}).get('key3', 'default_value')

이 안전한 액세스 패턴은 구조가 일관되지 않을 수 있는 API 응답 또는 기타 외부 JSON 데이터로 작업할 때 특히 유용합니다.

JSON 에서 중첩된 배열 작업하기

JSON 데이터는 종종 다른 객체 또는 배열을 포함할 수 있는 배열 (Python 에서는 리스트) 을 포함합니다. 중첩된 배열 내의 요소에 액세스하는 방법을 살펴보겠습니다.

  1. WebIDE 에서 새 파일을 만들고 /home/labex/project/json_practice 디렉토리에 nested_arrays.py로 저장합니다.

  2. nested_arrays.py에 다음 코드를 추가합니다.

import json

## JSON with nested arrays
company_data = {
    "name": "Tech Innovations Inc",
    "founded": 2010,
    "departments": [
        {
            "name": "Engineering",
            "employees": [
                {"name": "Alice Johnson", "role": "Software Engineer", "skills": ["Python", "JavaScript", "AWS"]},
                {"name": "Bob Smith", "role": "DevOps Engineer", "skills": ["Docker", "Kubernetes", "Linux"]}
            ]
        },
        {
            "name": "Marketing",
            "employees": [
                {"name": "Carol Williams", "role": "Marketing Manager", "skills": ["SEO", "Content Strategy"]},
                {"name": "Dave Brown", "role": "Social Media Specialist", "skills": ["Facebook Ads", "Instagram"]}
            ]
        }
    ],
    "locations": ["San Francisco", "New York", "London"]
}

## Print the JSON structure
print("Company Data:")
print(json.dumps(company_data, indent=2))
print("\n" + "-" * 50 + "\n")

## Accessing elements in arrays
print("Accessing array elements:")
print(f"First location: {company_data['locations'][0]}")
print(f"Number of departments: {len(company_data['departments'])}")
print(f"First department name: {company_data['departments'][0]['name']}")
print("\n" + "-" * 50 + "\n")

## Iterating through nested arrays
print("All employees and their skills:")
for department in company_data['departments']:
    dept_name = department['name']
    print(f"\nDepartment: {dept_name}")
    print("-" * 20)

    for employee in department['employees']:
        print(f"  {employee['name']} ({employee['role']})")
        print(f"  Skills: {', '.join(employee['skills'])}")
        print()

## Finding specific data in nested arrays
print("-" * 50 + "\n")
print("Finding employees with Python skills:")

for department in company_data['departments']:
    for employee in department['employees']:
        if "Python" in employee['skills']:
            print(f"  {employee['name']} in {department['name']} department")
  1. 터미널에서 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 nested_arrays.py

다음과 유사한 출력을 볼 수 있습니다.

Company Data:
{
  "name": "Tech Innovations Inc",
  "founded": 2010,
  "departments": [
    {
      "name": "Engineering",
      "employees": [
        {
          "name": "Alice Johnson",
          "role": "Software Engineer",
          "skills": [
            "Python",
            "JavaScript",
            "AWS"
          ]
        },
        {
          "name": "Bob Smith",
          "role": "DevOps Engineer",
          "skills": [
            "Docker",
            "Kubernetes",
            "Linux"
          ]
        }
      ]
    },
    {
      "name": "Marketing",
      "employees": [
        {
          "name": "Carol Williams",
          "role": "Marketing Manager",
          "skills": [
            "SEO",
            "Content Strategy"
          ]
        },
        {
          "name": "Dave Brown",
          "role": "Social Media Specialist",
          "skills": [
            "Facebook Ads",
            "Instagram"
          ]
        }
      ]
    }
  ],
  "locations": [
    "San Francisco",
    "New York",
    "London"
  ]
}

--------------------------------------------------

Accessing array elements:
First location: San Francisco
Number of departments: 2
First department name: Engineering

--------------------------------------------------

All employees and their skills:

Department: Engineering
--------------------
  Alice Johnson (Software Engineer)
  Skills: Python, JavaScript, AWS

  Bob Smith (DevOps Engineer)
  Skills: Docker, Kubernetes, Linux


Department: Marketing
--------------------
  Carol Williams (Marketing Manager)
  Skills: SEO, Content Strategy

  Dave Brown (Social Media Specialist)
  Skills: Facebook Ads, Instagram

--------------------------------------------------

Finding employees with Python skills:
  Alice Johnson in Engineering department

중첩된 배열 액세스 이해

JSON 에서 중첩된 배열로 작업하는 것은 다음의 조합을 포함합니다.

  1. 인덱싱된 액세스: 특정 배열 요소에 액세스하려면 인덱스와 함께 대괄호 사용 (array[0])
  2. 중첩된 속성 액세스: 딕셔너리 키와 배열 인덱스 연결 (data['departments'][0]['employees'])
  3. 반복: 배열에서 여러 항목을 처리하기 위해 루프 사용

중첩된 배열로 작업하기 위한 가장 일반적인 패턴은 중첩된 for 루프를 사용하는 것입니다.

for outer_item in json_data['outer_array']:
    for inner_item in outer_item['inner_array']:
        ## Process the inner_item
        print(inner_item['property'])

이 접근 방식을 사용하면 복잡한 중첩 구조를 탐색하고 필요한 특정 데이터를 추출할 수 있습니다.

누락된 키 처리 및 오류 방지

복잡한 JSON 구조, 특히 API 와 같은 외부 소스에서 가져온 JSON 구조로 작업할 때는 키가 누락될 때 발생하는 잠재적인 오류를 처리하는 것이 중요합니다. 중첩된 JSON 데이터에 안전하게 액세스하는 기술을 살펴보겠습니다.

  1. WebIDE 에서 새 파일을 만들고 /home/labex/project/json_practice 디렉토리에 error_handling.py로 저장합니다.

  2. error_handling.py에 다음 코드를 추가합니다.

import json

## JSON with inconsistent structure
api_response = {
    "status": "success",
    "data": {
        "users": [
            {
                "id": 1,
                "name": "John Doe",
                "contact": {
                    "email": "john.doe@example.com",
                    "phone": "555-1234"
                },
                "roles": ["admin", "user"]
            },
            {
                "id": 2,
                "name": "Jane Smith",
                ## Missing contact info
                "roles": ["user"]
            },
            {
                "id": 3,
                "name": "Bob Johnson",
                "contact": {
                    ## Only has email, no phone
                    "email": "bob.johnson@example.com"
                }
                ## Missing roles
            }
        ]
    }
}

print("API Response Structure:")
print(json.dumps(api_response, indent=2))
print("\n" + "-" * 50 + "\n")

## Approach 1: Using try-except blocks
print("Method 1: Using try-except blocks")
print("-" * 30)

for user in api_response["data"]["users"]:
    print(f"User: {user['name']}")

    ## Get email
    try:
        email = user['contact']['email']
        print(f"  Email: {email}")
    except (KeyError, TypeError):
        print("  Email: Not available")

    ## Get phone
    try:
        phone = user['contact']['phone']
        print(f"  Phone: {phone}")
    except (KeyError, TypeError):
        print("  Phone: Not available")

    ## Get roles
    try:
        roles = ", ".join(user['roles'])
        print(f"  Roles: {roles}")
    except (KeyError, TypeError):
        print("  Roles: None assigned")

    print()

## Approach 2: Using get() method with defaults
print("\n" + "-" * 50 + "\n")
print("Method 2: Using get() method with defaults")
print("-" * 30)

for user in api_response["data"]["users"]:
    print(f"User: {user['name']}")

    ## Get contact info with nested get() calls
    contact = user.get('contact', {})
    email = contact.get('email', 'Not available')
    phone = contact.get('phone', 'Not available')

    print(f"  Email: {email}")
    print(f"  Phone: {phone}")

    ## Get roles with default empty list
    roles = user.get('roles', [])
    roles_str = ", ".join(roles) if roles else "None assigned"
    print(f"  Roles: {roles_str}")

    print()
  1. 터미널에서 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 error_handling.py

다음과 유사한 출력을 볼 수 있습니다.

API Response Structure:
{
  "status": "success",
  "data": {
    "users": [
      {
        "id": 1,
        "name": "John Doe",
        "contact": {
          "email": "john.doe@example.com",
          "phone": "555-1234"
        },
        "roles": [
          "admin",
          "user"
        ]
      },
      {
        "id": 2,
        "name": "Jane Smith",
        "roles": [
          "user"
        ]
      },
      {
        "id": 3,
        "name": "Bob Johnson",
        "contact": {
          "email": "bob.johnson@example.com"
        }
      }
    ]
  }
}

--------------------------------------------------

Method 1: Using try-except blocks
------------------------------
User: John Doe
  Email: john.doe@example.com
  Phone: 555-1234
  Roles: admin, user

User: Jane Smith
  Email: Not available
  Phone: Not available
  Roles: user

User: Bob Johnson
  Email: bob.johnson@example.com
  Phone: Not available
  Roles: None assigned


--------------------------------------------------

Method 2: Using get() method with defaults
------------------------------
User: John Doe
  Email: john.doe@example.com
  Phone: 555-1234
  Roles: admin, user

User: Jane Smith
  Email: Not available
  Phone: Not available
  Roles: user

User: Bob Johnson
  Email: bob.johnson@example.com
  Phone: Not available
  Roles: None assigned

오류 처리 기술 이해

이 예제에서는 중첩된 JSON 데이터에 안전하게 액세스하기 위한 두 가지 주요 접근 방식을 보여줍니다.

  1. Try-Except 블록

    • 잠재적으로 위험한 액세스를 try-except 블록으로 묶습니다.
    • KeyError(누락된 딕셔너리 키) 및 TypeError(비 딕셔너리에 키에 액세스하려는 시도) 를 캡처합니다.
    • 오류가 발생할 때 대체 값을 제공합니다.
  2. Chained get() 메서드

    • 두 번째 인수로 기본값을 사용하는 딕셔너리 get() 메서드를 사용합니다.
    • 중첩된 구조에 대해 여러 get() 호출을 연결합니다.
    • 예외 처리 없이 더 깔끔한 코드를 제공합니다.

get() 메서드 접근 방식은 중첩된 JSON 구조를 처리할 때 가독성과 간결성으로 인해 일반적으로 선호됩니다. 이를 통해 중첩의 각 수준에서 기본값을 제공할 수 있습니다.

## Safe nested access pattern
value = data.get('level1', {}).get('level2', {}).get('level3', 'default_value')

이러한 오류 처리 기술을 사용하면 다양한 소스의 JSON 데이터로 작업할 때 코드가 더 강력해집니다.

실습: JSON 데이터 추출기 구축

복잡한 JSON 구조에서 특정 정보를 추출하는 프로그램을 만들어 지식을 실천에 옮겨 봅시다. 이는 API 에서 JSON 데이터를 수신하고 이를 처리해야 하는 실제 시나리오를 나타낼 수 있습니다.

  1. WebIDE 에서 새 파일을 만들고 /home/labex/project/json_practice 디렉토리에 json_extractor.py로 저장합니다.

  2. json_extractor.py에 다음 코드를 추가합니다.

import json

## A complex nested JSON structure (e.g., from a weather API)
weather_data = {
    "location": {
        "name": "New York",
        "region": "New York",
        "country": "United States of America",
        "lat": 40.71,
        "lon": -74.01,
        "timezone": "America/New_York"
    },
    "current": {
        "temp_c": 22.0,
        "temp_f": 71.6,
        "condition": {
            "text": "Partly cloudy",
            "icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
            "code": 1003
        },
        "wind_mph": 6.9,
        "wind_kph": 11.2,
        "wind_dir": "ENE",
        "humidity": 65,
        "cloud": 75,
        "feelslike_c": 22.0,
        "feelslike_f": 71.6
    },
    "forecast": {
        "forecastday": [
            {
                "date": "2023-09-20",
                "day": {
                    "maxtemp_c": 24.3,
                    "maxtemp_f": 75.7,
                    "mintemp_c": 18.6,
                    "mintemp_f": 65.5,
                    "condition": {
                        "text": "Patchy rain possible",
                        "icon": "//cdn.weatherapi.com/weather/64x64/day/176.png",
                        "code": 1063
                    },
                    "daily_chance_of_rain": 85
                },
                "astro": {
                    "sunrise": "06:41 AM",
                    "sunset": "07:01 PM",
                    "moonrise": "10:15 AM",
                    "moonset": "08:52 PM"
                },
                "hour": [
                    {
                        "time": "2023-09-20 00:00",
                        "temp_c": 20.1,
                        "condition": {
                            "text": "Clear",
                            "icon": "//cdn.weatherapi.com/weather/64x64/night/113.png",
                            "code": 1000
                        },
                        "chance_of_rain": 0
                    },
                    {
                        "time": "2023-09-20 12:00",
                        "temp_c": 23.9,
                        "condition": {
                            "text": "Overcast",
                            "icon": "//cdn.weatherapi.com/weather/64x64/day/122.png",
                            "code": 1009
                        },
                        "chance_of_rain": 20
                    }
                ]
            },
            {
                "date": "2023-09-21",
                "day": {
                    "maxtemp_c": 21.2,
                    "maxtemp_f": 70.2,
                    "mintemp_c": 16.7,
                    "mintemp_f": 62.1,
                    "condition": {
                        "text": "Heavy rain",
                        "icon": "//cdn.weatherapi.com/weather/64x64/day/308.png",
                        "code": 1195
                    },
                    "daily_chance_of_rain": 92
                },
                "astro": {
                    "sunrise": "06:42 AM",
                    "sunset": "06:59 PM",
                    "moonrise": "11:30 AM",
                    "moonset": "09:15 PM"
                }
            }
        ]
    }
}

def extract_weather_summary(data):
    """
    Extract and format a weather summary from the provided data.
    """
    try:
        ## Location information
        location = data.get("location", {})
        location_name = location.get("name", "Unknown")
        country = location.get("country", "Unknown")

        ## Current weather
        current = data.get("current", {})
        temp_c = current.get("temp_c", "N/A")
        temp_f = current.get("temp_f", "N/A")
        condition = current.get("condition", {}).get("text", "Unknown")
        humidity = current.get("humidity", "N/A")

        ## Forecast
        forecast_days = data.get("forecast", {}).get("forecastday", [])

        ## Build summary string
        summary = f"Weather Summary for {location_name}, {country}\n"
        summary += f"==================================================\n\n"
        summary += f"Current Conditions:\n"
        summary += f"  Temperature: {temp_c}°C ({temp_f}°F)\n"
        summary += f"  Condition: {condition}\n"
        summary += f"  Humidity: {humidity}%\n\n"

        if forecast_days:
            summary += "Forecast:\n"
            for day_data in forecast_days:
                date = day_data.get("date", "Unknown date")
                day = day_data.get("day", {})
                max_temp = day.get("maxtemp_c", "N/A")
                min_temp = day.get("mintemp_c", "N/A")
                condition = day.get("condition", {}).get("text", "Unknown")
                rain_chance = day.get("daily_chance_of_rain", "N/A")

                summary += f"  {date}:\n"
                summary += f"    High: {max_temp}°C, Low: {min_temp}°C\n"
                summary += f"    Condition: {condition}\n"
                summary += f"    Chance of Rain: {rain_chance}%\n"

                ## Get sunrise and sunset times if available
                astro = day_data.get("astro", {})
                if astro:
                    sunrise = astro.get("sunrise", "N/A")
                    sunset = astro.get("sunset", "N/A")
                    summary += f"    Sunrise: {sunrise}, Sunset: {sunset}\n"

                summary += "\n"

        return summary

    except Exception as e:
        return f"Error extracting weather data: {str(e)}"

## Print the full JSON data
print("Original Weather Data:")
print(json.dumps(weather_data, indent=2))
print("\n" + "-" * 60 + "\n")

## Extract and print the weather summary
weather_summary = extract_weather_summary(weather_data)
print(weather_summary)

## Save the summary to a file
with open("weather_summary.txt", "w") as file:
    file.write(weather_summary)

print("\nWeather summary has been saved to 'weather_summary.txt'")
  1. 터미널에서 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 json_extractor.py
  1. 스크립트를 실행한 후 생성된 요약 파일을 볼 수 있습니다.
cat weather_summary.txt

복잡한 JSON 구조에서 추출된 형식화된 날씨 요약을 볼 수 있습니다.

JSON 추출기 이해

이 실습에서는 중첩된 JSON 데이터로 작업하기 위한 몇 가지 중요한 개념을 보여줍니다.

  1. 안전한 데이터 추출

    • 누락된 키를 처리하기 위해 기본값을 사용하여 get() 메서드 사용
    • 연결된 get() 호출로 중첩된 데이터에 액세스
    • try-except 블록을 사용한 오류 처리
  2. 데이터 변환

    • JSON 데이터를 사람이 읽을 수 있는 형식으로 변환
    • 여러 항목을 처리하기 위해 중첩된 배열을 반복
    • 복잡한 구조에서 관련 정보만 추출
  3. 방어적 프로그래밍

    • 잠재적인 문제를 예상하고 처리
    • 데이터가 누락된 경우 기본값 제공
    • 프로그램 충돌을 방지하기 위해 예외를 포착

JSON 데이터를 추출, 변환 및 표시하는 이 패턴은 다음과 같은 많은 실제 응용 프로그램에서 일반적입니다.

  • API 응답 처리
  • 데이터에서 보고서 생성
  • 사용자에게 정보 필터링 및 표시

이러한 패턴을 따르면 복잡성에 관계없이 JSON 데이터를 안정적으로 사용할 수 있습니다.

요약

이 랩에서는 Python 에서 중첩된 JSON 구조로 작업하는 방법을 배웠습니다.

  1. 기본 JSON 처리 - json.dumps()json.loads()를 사용하여 Python 객체와 JSON 문자열 간 변환.

  2. 중첩된 딕셔너리 키에 액세스 - JSON 객체 내에서 깊이 중첩된 값에 액세스하기 위해 연결된 대괄호 표기법 사용.

  3. 중첩된 배열 작업 - 인덱싱 및 반복을 사용하여 JSON 구조 내의 배열에서 데이터를 탐색하고 추출.

  4. 오류 처리 기술 - 누락된 키를 처리하기 위해 try-except 블록 및 get() 메서드를 사용하여 안전한 액세스 패턴 구현.

  5. 실용적인 데이터 추출 - 복잡한 JSON 구조에서 데이터를 추출, 변환 및 표시하는 완전한 애플리케이션 구축.

이러한 기술은 API, 구성 파일 및 기타 데이터 교환 시나리오에서 데이터를 사용하는 데 필수적입니다. 이제 Python 애플리케이션에서 복잡성에 관계없이 JSON 데이터를 자신 있게 처리할 수 있는 기반을 갖추었습니다.

추가 학습을 위해 다음을 고려해 보세요.

  • JSON 데이터를 반환하는 실제 API 사용
  • pandas와 같은 라이브러리를 사용하여 JSON 데이터 분석
  • jsonschema를 사용하여 JSON 유효성 검사 구현
  • 사용자 지정 JSON 구조 생성 및 조작