#K77117. Flatten JSON
Flatten JSON
Flatten JSON
Your task is to write a program to flatten a nested JSON object into a single-level JSON object. In the flattened object, every key corresponds to a path in the original JSON using a period (.) as a separator. For example, given the input JSON:
{ "user": { "name": "Alex", "address": { "street": "123 Maple Street", "city": "Metropolis", "zip": "10001" } }, "items": [ {"item_id": 1, "description": "A book"}, {"item_id": 2, "description": "A pen"} ] }
The output should be:
{ "user.name": "Alex", "user.address.street": "123 Maple Street", "user.address.city": "Metropolis", "user.address.zip": "10001", "items.0.item_id": 1, "items.0.description": "A book", "items.1.item_id": 2, "items.1.description": "A pen" }
Use recursion to traverse nested dictionaries and lists. If a value is directly a primitive type (e.g. number, string, or null), output it directly with its key. If the JSON is empty, output an empty JSON object.
You may find the following LaTeX formula useful which describes the key concatenation:
$$ key_{new} = key_{parent} \cdot \text{.} \cdot key_{current} $$
inputFormat
The input consists of a single JSON string read from standard input. This JSON string represents a possibly nested JSON object. It may include nested dictionaries and arrays.
outputFormat
Output the flattened JSON object as a JSON string on standard output. The flattened JSON should have no nested structures; all keys represent the path in the original JSON separated by a period (.)
## sample{"user": {"name": "Alex", "address": {"street": "123 Maple Street", "city": "Metropolis", "zip": "10001"}}, "items": [{"item_id": 1, "description": "A book"}, {"item_id": 2, "description": "A pen"}]}
{"user.name":"Alex","user.address.street":"123 Maple Street","user.address.city":"Metropolis","user.address.zip":"10001","items.0.item_id":1,"items.0.description":"A book","items.1.item_id":2,"items.1.description":"A pen"}