Explain Codes LogoExplain Codes Logo

Convert JSON string to dict using Python

python
json-loads
json-dumps
error-handling
Alex KataevbyAlex Kataev·Sep 12, 2024
TLDR

A JSON string is transformed into a Python dict with json.loads().

import json dict_obj = json.loads('{"key": "value"}')

Access the corresponding value with dict_obj['key'].

Handle with care: Valid JSON format

To dance salsa, two to tango, but to decode JSON... It's gotta be formatted right! Validate your JSON string like a bouncer at a club, or json.loads() will greet you with a json.JSONDecodeError.

Catch me if you can: Error handling

try-except is your catch-net, hoist it before json.loads():

try: dict_obj = json.loads(json_string) # trying to decode the JSON string except json.JSONDecodeError as e: print(f"Decode Error: even a decoder ring wouldn't help this. Problem: {e}") # fallback for invalid JSON

Back and forth: Revert to JSON string

To revert the dictionary back to a JSON string, json.dumps() is your friend, as well as one who reminds you from where you started.

json_str = json.dumps(dict_obj)

Visualization

Unpack a JSON string suitcase into a Python dict chest of drawers:

JSON String Baggage (🧳): '{"name": "Alice", "age": 30, "city": "Wonderland"}'

By using:

import json dict_from_json = json.loads(json_string)

You delegate the unpacking to an invisible Python assistant (🧚‍♂️):

Python Dict Storage Unit (🗄️): - Drawer [Name]: "Alice" 🏷️ - Drawer [Age]: 30 🎂 - Drawer [City]: "Wonderland" 🏰

Each piece of data, neatly stored, and as easily retrievable as opening a drawer!

Digging deeper: Nested JSON

Nested structure? No worries. Access inner elements by chaining keys like a prospector:

nested_value = dict_from_json['outer']['inner'] # dig deep!

Play safe: 'eval' and security

Tempted to use eval()? Be careful! It can execute arbitrary code – like inviting a stranger into your home. Always know your sources.

Pick yours: Alternative parsers

Parsing library is a menu! Try simplejson or cjson.decode(obj) if you have special dietary requirements.

Check twice: Type verification

After pulling your dictionary out of JSON string, don’t trust, but verify the type:

if not isinstance(dict_obj, dict): print("This isn't a dictionary, it's a...") # fallback for wrong type data

Advanced maneuvers

JSON arrays meet Python lists

Meet the JSON array's Python cousin: the list. Access elements just like at grandma's house - by the index:

array_obj = json.loads('["item1", "item2"]') # Here comes the Python list! first_item = array_obj[0] # You always remember the first!

Time traveling: handling Date and Time

JSON strings – a world without time. Until you bring it to life as a Python datetime object:

from datetime import datetime dict_with_date = json.loads('{"date": "2023-04-01"}') date_obj = datetime.strptime(dict_with_date["date"], '%Y-%m-%d') # Happy future birthday!

Secret paths: Non-standard JSON

Dealing with rebel JSONs with extras like comments or trailing commas? Libraries like demjson can get along with these bad boys.

import demjson non_standard_json = '{"key": "value", /* rebel comment */ }' dict_obj = demjson.decode(non_standard_json) # Meet the rebel.