October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober 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

How to Convert a String to JSON in Python

Use Python’s json.loads() to parse JSON text in a string. Learn what it returns, when to use load or dumps, and how to handle malformed input.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To parse JSON text held in a Python string, use json.loads(text). It returns the Python value represented by the JSON—such as a dictionary, list, string, number, boolean, or None. To go the other direction, from a Python value to JSON text, use json.dumps(value).

Parse a JSON string with json.loads

Import Python’s standard-library json module, then pass the JSON text to loads:

import json

text = '{"name": "Ada", "active": true, "items": [1, 2, 3]}'
value = json.loads(text)

print(value)
# {'name': 'Ada', 'active': True, 'items': [1, 2, 3]}

The JSON booleans true and false become Python’s True and False; JSON null becomes None. The operation parses the text—it does not turn the string into a dictionary in every case.

Choose the function for the input and direction

What you have What you want Function
JSON text in a string, bytes, or bytearray A Python value json.loads(text)
An open file or other object with a .read() method containing JSON A Python value json.load(file_obj)
A Python value A JSON-formatted string json.dumps(value)
A Python value and a file-like object JSON written to that object json.dump(value, file_obj)

The similar names are easy to mix up: loads accepts JSON text already in a variable, while load reads from a file-like object. Passing a string to json.load usually causes an error because a plain string is not a file object.

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

Know what type loads returns

The result depends on the top-level JSON value. Python’s documented conversions are:

  • JSON object → Python dict
  • JSON array → Python list
  • JSON string → Python str
  • JSON integer → Python int
  • JSON real number → Python float
  • JSON true or false → Python True or False
  • JSON null → Python None
json.loads('{"language": "Python"}')  # dict
json.loads('[1, 2, 3]')                 # list
json.loads('42')                        # int
json.loads('true')                      # True
json.loads('null')                      # None

If your code specifically needs an object, check the result before using dictionary operations:

value = json.loads(text)

if isinstance(value, dict):
    print(value.get("name"))
else:
    print("Expected a JSON object")

Fix invalid JSON instead of disguising it

Malformed JSON raises json.JSONDecodeError. Catch that exception when invalid input is an expected possibility, and use its message and location to find the syntax problem:

import json

text = '{"name": "Ada",}'  # trailing comma is invalid JSON

try:
    value = json.loads(text)
except json.JSONDecodeError as exc:
    print(f"Invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}")

Common causes include single quotes around strings or keys, unquoted object keys, trailing commas, Python’s True, False, and None instead of JSON’s lowercase true, false, and null, and literal newlines or control characters inside a JSON string. JSON strings and object keys use double quotes.

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

If the input is a Python literal rather than JSON, it is a different format; json.loads is not the right parser. Do not use eval to parse input. Fix or safely handle the actual format rather than catching every error and silently substituting an empty dictionary, which can hide corrupted data.

Handle content after a JSON document deliberately

json.loads is the right choice when the input is one complete JSON document. If a protocol intentionally places additional content after a JSON document, use JSONDecoder.raw_decode to obtain both the decoded value and the character index where that JSON ended:

decoder = json.JSONDecoder()
value, end = decoder.raw_decode(text)
remaining = text[end:]

raw_decode does not decide what the remaining text means. Your code must handle, validate, or reject it according to the protocol; do not use this method to overlook unexpected trailing content.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Be careful with untrusted or non-standard values

Python’s JSON decoder accepts NaN, Infinity, and -Infinity as extensions, although those values are outside the JSON specification. If strict interoperability matters, reject them with parse_constant:

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

def reject_constant(value):
    raise ValueError(f"Non-standard JSON constant: {value}")

value = json.loads(text, parse_constant=reject_constant)

Successful parsing is not application-level validation: check that required fields exist and have the expected types and values. The Python 3.14 library documentation also cautions that malicious JSON may consume considerable CPU and memory and recommends limiting the size of data to be parsed. Apply an appropriate size limit before parsing untrusted input.

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
Windows Errors? Fix Them Before They SpreadFree repair scan

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.