October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Convert a JSON String to a Dictionary in Python: 5 Ways

Use Python’s json.loads() to decode JSON text. Learn why only a top-level JSON object becomes a dictionary, plus four useful decoder customizations.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a string containing JSON, use Python’s json.loads(). When the JSON’s top-level value is an object, it returns a Python dictionary. JSON arrays and other top-level values decode to different Python types.

1. Parse a JSON string with json.loads()

This is the standard choice when you already have JSON text. Python’s json module documentation describes json.loads() as deserializing a JSON document supplied as a string, bytes, or bytearray into a Python object.

import json

json_text = '{"name": "Ada", "active": true, "scores": [10, 12]}'
data = json.loads(json_text)

print(data["name"])  # Ada
print(type(data))     # <class 'dict'>

JSON syntax uses double quotes around strings and object keys, and the literals true, false, and null. Python converts these to True, False, and None when decoding.

Check the decoded type before treating it as a dictionary

The result depends on the JSON value at the document’s top level. A JSON object becomes a Python dict, but an array becomes a list; a string, integer, real number, boolean, or null becomes str, int, float, bool, or None, respectively. Only an object at the top level produces a dictionary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If your code expects a dictionary, check the input’s shape or verify the result before using string keys:

data = json.loads(json_text)

if isinstance(data, dict):
    print(data["name"])
else:
    raise TypeError("Expected a JSON object at the top level")

2. Decode explicitly with JSONDecoder

If you need to work with the decoder object directly, create a JSONDecoder and call its decode() method. For ordinary parsing, it gives you the same kind of decoded Python value as json.loads().

import json

decoder = json.JSONDecoder()
data = decoder.decode(json_text)

3. Transform objects with object_hook

Use object_hook when a JSON object has a known shape that should become another Python value. The function receives each decoded object as a dictionary and returns the value that should replace it. For example, tagged point objects can be turned into coordinate tuples:

import json

def object_hook(obj):
    if obj.get("__type__") == "point":
        return (obj["x"], obj["y"])
    return obj

json_text = '{"location": {"__type__": "point", "x": 3, "y": 4}}'
data = json.loads(json_text, object_hook=object_hook)
print(data["location"])  # (3, 4)

4. Handle object members as ordered pairs with object_pairs_hook

object_pairs_hook receives each JSON object’s members as an ordered list of pairs. It can return a dictionary or another representation you choose. For example, passing dict builds a dictionary from those pairs:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
data = json.loads(json_text, object_pairs_hook=dict)

If you provide both object_pairs_hook and object_hook, object_pairs_hook takes priority.

5. Choose numeric types with parsing hooks

Use parse_float or parse_int when the default Python numeric type is not the right fit. The hooks receive a JSON number’s text and let you apply a different conversion policy. For example, decoding decimal values as Decimal can avoid converting them to binary floating-point numbers:

import json
from decimal import Decimal

json_text = '{"price": 12.50}'
data = json.loads(json_text, parse_float=Decimal)
print(data["price"])  # Decimal('12.50')

Use these hooks for a specific numeric requirement; ordinary JSON numbers need no customization.

Use json.load() for a file, not a string

The distinction is the input: json.loads(text) parses JSON text, while json.load(file) reads and parses a file-like object.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import json

with open("data.json", encoding="utf-8") as file:
    data = json.load(file)
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Fix common parsing errors

Invalid JSON raises JSONDecodeError

If the text is malformed, json.loads() raises json.JSONDecodeError. Inspect the original input and the exception’s location details to find the problem.

Python-looking text may not be JSON

A string such as {'name': 'Ada'} uses single quotes and is a Python-style representation, not valid JSON. JSON requires double quotes around strings and keys. If the source is meant to be JSON, correct its serialization rather than passing it to eval(); eval() executes Python expressions and is not a JSON parser.

Python accepts some non-standard numeric constants

Python’s JSON decoder accepts NaN, Infinity, and -Infinity by default, although these are outside the JSON specification. If strict standards compliance matters, account for these values rather than assuming the default decoder rejects them.

Very large integer strings can be limited

Since Python 3.11, the default integer-parsing path uses the interpreter’s integer-string length limitation as a denial-of-service mitigation. This matters mainly when handling untrusted input or unusually large numeric values.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.