PY
py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from dataclasses import dataclass
import json
@dataclass
class Product:
name: str
price: float
category: str = None
description: str = None
# Sample JSON string
json_string = """
{
"name": "Mac M1 Laptop",
"price": 1999.99,
"category": "Electronics",
"description": "A powerful laptop for work and play"
}
"""
def select_fields(data):
# Pick only the desired fields and assign defaults for others
return Product(data["name"], data["price"])
# Deserialize the JSON string with custom hook
product = json.loads(json_string, object_hook=select_fields)
# Accessing only included data
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run