[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"blog-post-how-to-read-a-json-file-in-python-en":3},{"post":4,"faq":34,"faqLdJson":60,"faqLdJsonScript":91,"alternatePaths":92,"recommendations":94,"contentLocale":20},{"authors":5,"custom_excerpt":13,"excerpt":13,"feature_image":14,"featured":15,"id":16,"meta_description":13,"meta_title":17,"og_description":8,"og_image":8,"og_title":8,"primary_author":18,"primary_tag":19,"published_at":22,"reading_time":23,"slug":24,"status":25,"tags":26,"title":17,"twitter_description":8,"twitter_image":8,"twitter_title":31,"updated_at":32,"visibility":21,"lexical":33},[6],{"bio":7,"facebook":8,"instagram":8,"linkedin":8,"location":9,"name":10,"profile_image":11,"slug":12,"tiktok":8,"twitter":8,"website":8,"youtube":8},"A Columnist at Rola IP, Chloe is deeply curious about digital marketing and search engine logic. Outside of work, she enjoys experimenting with web layout tools, photography, and image processing.",null,"Chloe是Rola IP的专栏作者。生活中，她对数字营销和搜索引擎背后的逻辑充满好奇。除了研究各种实用的网页排版工具，她还热爱摄影与图像处理。","Chloe Sun","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002FPixPin_2026-08-13_11-09-19.png","chloe","Learn how to read a JSON file in Python with json.load(), handle paths and decode errors, access nested values, and process JSON Lines safely.","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F-------6.webp",false,"6a86a3634956c90001bed49d","How to Read a JSON File in Python (With Examples)",{"bio":7,"facebook":8,"instagram":8,"linkedin":8,"location":9,"name":10,"profile_image":11,"slug":12,"tiktok":8,"twitter":8,"website":8,"youtube":8},{"description":8,"feature_image":8,"name":20,"slug":20,"visibility":21},"en","public","2026-08-20T07:20:05.000Z",8,"how-to-read-a-json-file-in-python","published",[27,28],{"description":8,"feature_image":8,"name":20,"slug":20,"visibility":21},{"description":8,"feature_image":8,"name":29,"slug":30,"visibility":21},"教程","guides","how to read a json file in python","2026-10-09T11:16:14.000Z","{\"root\":{\"children\":[{\"type\":\"markdown\",\"version\":1,\"markdown\":\"## TL;DR\\n\\nTo read a JSON file in Python, import the standard-library `json` module, open the file with UTF-8 encoding, and pass the file object to `json.load()`:\\n\\n```python\\nimport json\\n\\nwith open(\\\"settings.json\\\", encoding=\\\"utf-8\\\") as file:\\n    data = json.load(file)\\n\\nprint(data)\\n```\\n\\n`json.load()` returns regular Python objects. A JSON object becomes a `dict`, while a JSON array becomes a `list`. Use `json.loads()` instead when the JSON is already in a string rather than a file.\\n\\n![Imperial College tutorial showing json.load for a JSON file](https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F03-imperial-json-load-example.webp)\\n\\n*A concise file-loading example from Imperial College London's Python tutorial.*\\n\\n## Start with a small JSON file\\n\\nSuppose `settings.json` contains this data:\\n\\n```json\\n{\\n  \\\"project\\\": \\\"Rola research\\\",\\n  \\\"active\\\": true,\\n  \\\"regions\\\": [\\\"us\\\", \\\"de\\\"],\\n  \\\"limits\\\": {\\n    \\\"requests_per_minute\\\": 120,\\n    \\\"timeout_seconds\\\": 20\\n  },\\n  \\\"price\\\": 19.99,\\n  \\\"notes\\\": \\\"café ☕\\\"\\n}\\n```\\n\\nRead the file and access its values like this:\\n\\n```python\\nimport json\\n\\nwith open(\\\"settings.json\\\", encoding=\\\"utf-8\\\") as file:\\n    data = json.load(file)\\n\\nprint(type(data).__name__)\\nprint(data[\\\"project\\\"])\\nprint(data[\\\"limits\\\"][\\\"timeout_seconds\\\"])\\nprint(data[\\\"notes\\\"])\\n```\\n\\nExpected output:\\n\\n```text\\ndict\\nRola research\\n20\\ncafé ☕\\n```\\n\\nThe `with` statement closes the file automatically, including when parsing raises an exception. Setting `encoding=\\\"utf-8\\\"` also makes the expected text encoding explicit. That matters once a file contains names, accented characters, or non-Latin text.\\n\\n![freeCodeCamp Python JSON tutorial page](https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F04-freecodecamp-json-load-example-1.webp)\\n\\n*The freeCodeCamp walkthrough shows the same beginner pattern in a complete tutorial context.*\\n\\n## `json.load()` and `json.loads()` solve different problems\\n\\nTheir names differ by one letter, which causes plenty of avoidable errors:\\n\\n| Input you have | Function to use | Example |\\n|---|---|---|\\n| An open file object | `json.load()` | `data = json.load(file)` |\\n| A string, bytes, or bytearray containing JSON | `json.loads()` | `data = json.loads(json_text)` |\\n\\nFor a string:\\n\\n```python\\nimport json\\n\\njson_text = '{\\\"status\\\": \\\"ok\\\", \\\"count\\\": 3}'\\ndata = json.loads(json_text)\\n\\nprint(data[\\\"count\\\"])\\n```\\n\\nDo not pass a file object to `json.loads()`. Do not pass a file path string to it either. A value such as `\\\"settings.json\\\"` is only a filename, not the contents of that file.\\n\\n![python-json-load-reference](https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F02-python-json-load-reference.webp)\\n\\n*Python's official reference documents the `json.load()` parameters and the parsing exceptions it can raise.*\\n\\n## Use `pathlib` when relative paths become confusing\\n\\nPython resolves a relative path from the process's current working directory, which may differ from the folder containing the script. This is why code can work in an editor and fail from a scheduler, test runner, or another terminal directory.\\n\\nIf the JSON file sits next to the script, build the path from `__file__`:\\n\\n```python\\nimport json\\nfrom pathlib import Path\\n\\njson_path = Path(__file__).resolve().parent \u002F \\\"settings.json\\\"\\n\\nwith json_path.open(encoding=\\\"utf-8\\\") as file:\\n    data = json.load(file)\\n```\\n\\nThis pattern is intended for Python scripts. In notebooks and interactive environments, `__file__` may not be defined. Use `Path.cwd()` only when the working directory is intentional, or pass an explicitly configured base directory.\\n\\nWhen debugging a missing file, print the resolved path before changing anything else:\\n\\n```python\\nprint(json_path.resolve())\\nprint(json_path.exists())\\n```\\n\\nIf `exists()` returns `False`, the problem is the path or filename. The JSON parser has not run yet.\\n\\n## What Python types will you get?\\n\\nThe decoder maps JSON values to familiar Python values:\\n\\n| JSON value | Python value |\\n|---|---|\\n| object | `dict` |\\n| array | `list` |\\n| string | `str` |\\n| integer | `int` |\\n| decimal number | `float` by default |\\n| `true` or `false` | `True` or `False` |\\n| `null` | `None` |\\n\\nThe top-level value does not have to be an object. If a file begins with `[` and contains an array, `json.load()` returns a list:\\n\\n```python\\nwith open(\\\"users.json\\\", encoding=\\\"utf-8\\\") as file:\\n    users = json.load(file)\\n\\nfor user in users:\\n    print(user[\\\"name\\\"])\\n```\\n\\nCheck `type(data)` or the first non-whitespace character in the file if you expected a dictionary but received a list.\\n\\n## Read nested values without turning every missing key into a crash\\n\\nSquare brackets are appropriate when a field is required. They raise `KeyError` if the key is absent, which can expose bad or incomplete input early:\\n\\n```python\\ntimeout = data[\\\"limits\\\"][\\\"timeout_seconds\\\"]\\n```\\n\\nFor optional fields, `.get()` lets you supply a default:\\n\\n```python\\nretry_count = data.get(\\\"limits\\\", {}).get(\\\"retry_count\\\", 0)\\n```\\n\\nThat expression handles a missing `limits` object, but it does not handle every possible wrong type. If untrusted input might contain `\\\"limits\\\": null` or a string in that position, validate the structure before using it:\\n\\n```python\\nlimits = data.get(\\\"limits\\\")\\n\\nif isinstance(limits, dict):\\n    retry_count = limits.get(\\\"retry_count\\\", 0)\\nelse:\\n    retry_count = 0\\n```\\n\\nFor arrays, use an index only after checking that the item exists:\\n\\n```python\\nregions = data.get(\\\"regions\\\", [])\\nfirst_region = regions[0] if regions else None\\n```\\n\\nThis is longer than a chain of brackets, but the fallback is visible. Readers maintaining the code later can tell which fields are mandatory and which are optional.\\n\\n## Handle file and JSON errors separately\\n\\nSeveral failures can happen before or during parsing. Catching them separately makes the error message useful.\\n\\n```python\\nimport json\\nfrom pathlib import Path\\n\\njson_path = Path(\\\"settings.json\\\")\\n\\ntry:\\n    with json_path.open(encoding=\\\"utf-8\\\") as file:\\n        data = json.load(file)\\nexcept FileNotFoundError:\\n    print(f\\\"File not found: {json_path.resolve()}\\\")\\nexcept IsADirectoryError:\\n    print(f\\\"Expected a file but found a directory: {json_path.resolve()}\\\")\\nexcept PermissionError:\\n    print(f\\\"Permission denied: {json_path.resolve()}\\\")\\nexcept UnicodeDecodeError as error:\\n    print(f\\\"The file is not valid UTF-8: {error}\\\")\\nexcept json.JSONDecodeError as error:\\n    print(\\n        f\\\"Invalid JSON at line {error.lineno}, \\\"\\n        f\\\"column {error.colno}: {error.msg}\\\"\\n    )\\n```\\n\\nThese exceptions point to different fixes:\\n\\n- `FileNotFoundError`: verify the current directory, resolved path, spelling, and filename case.\\n- `IsADirectoryError`: confirm that the path points to a JSON file rather than a directory.\\n- `PermissionError`: check whether the current user has permission to read the file.\\n- `UnicodeDecodeError`: confirm the file's actual encoding. Do not silence it with `errors=\\\"ignore\\\"`, because dropped characters can change the data.\\n- `JSONDecodeError`: inspect the reported line and column for invalid syntax.\\n\\nCommon JSON syntax mistakes include single quotes, trailing commas, comments, unquoted property names, and Python values such as `True` or `None`. Valid JSON uses double quotes, has no comments, and spells those values `true` and `null`.\\n\\nYou can also validate a file from the terminal:\\n\\n```bash\\npython -m json.tool settings.json\\n```\\n\\nThe command prints formatted JSON when the file is valid. When parsing fails, it reports the location of the syntax error.\\n\\n## Read JSON Lines one record at a time\\n\\nA `.jsonl` or `.ndjson` file usually stores one complete JSON value per line:\\n\\n```json\\n{\\\"id\\\": 1, \\\"status\\\": \\\"ok\\\"}\\n{\\\"id\\\": 2, \\\"status\\\": \\\"retry\\\"}\\n{\\\"id\\\": 3, \\\"status\\\": \\\"ok\\\"}\\n```\\n\\nThe entire file is not one JSON document, so `json.load()` will fail after the first object. Parse each nonempty line with `json.loads()` instead:\\n\\n```python\\nimport json\\n\\nrecords = []\\n\\nwith open(\\\"records.jsonl\\\", encoding=\\\"utf-8\\\") as file:\\n    for line_number, line in enumerate(file, start=1):\\n        if not line.strip():\\n            raise ValueError(f\\\"Blank line at record line {line_number}\\\")\\n\\n        try:\\n            records.append(json.loads(line))\\n        except json.JSONDecodeError as error:\\n            raise ValueError(\\n                f\\\"Invalid JSON on record line {line_number}: {error.msg}\\\"\\n            ) from error\\n```\\n\\nStrict JSON Lines requires every line to contain a valid JSON value. `null` is valid, but a blank line is not. If your input intentionally permits blank lines, replace the exception with `continue` and document that permissive behavior.\\n\\nThis is also the right pattern when you want to process each record and discard it rather than keep the full list in memory.\\n\\n![Python JSON documentation note about multiple objectsp](https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F01-python-json-basic-usage.webp)\\n\\n*The official documentation notes that JSON is not a framed protocol. Separate objects need a container format such as JSON Lines or a valid enclosing array.*\\n\\n## Large JSON files need a different plan\\n\\n`json.load()` reads and decodes one complete JSON document into memory. A 2 GB file can therefore require much more than 2 GB of available memory once its strings, dictionaries, and lists become Python objects.\\n\\nChoose the approach based on the format you control:\\n\\n- For JSON Lines, iterate over the file and process one line at a time.\\n- For one huge JSON array or object, use a streaming parser such as `ijson`, or change the export format if you control the producer.\\n- For data analysis, a format designed for tabular or columnar processing may fit better than one enormous JSON document.\\n\\nDo not split ordinary JSON at arbitrary newline or byte positions. A string can contain escaped characters, and nested objects can span many lines. Chunking without a parser can corrupt record boundaries.\\n\\n## Preserve decimal values when binary floats are unsuitable\\n\\nJSON numbers with a decimal point become Python `float` values by default. That is fine for many measurements, but some workflows need decimal arithmetic with the original decimal representation.\\n\\nPass `Decimal` as `parse_float`:\\n\\n```python\\nimport json\\nfrom decimal import Decimal\\n\\nwith open(\\\"settings.json\\\", encoding=\\\"utf-8\\\") as file:\\n    data = json.load(file, parse_float=Decimal)\\n\\nprint(type(data[\\\"price\\\"]).__name__, data[\\\"price\\\"])\\n```\\n\\nExpected output:\\n\\n```text\\nDecimal 19.99\\n```\\n\\nThis choice changes how the decoder creates non-integer numbers. It does not validate that a value represents a price, percentage, or any other business concept.\\n\\n## When the JSON comes from an API or web request\\n\\nLocal parsing and network retrieval are separate stages. A proxy cannot repair a missing local file, incorrect encoding, or malformed JSON already saved to disk.\\n\\nFor an HTTP response, check the status and content type before decoding it. A server may return an HTML error page even when the URL normally serves JSON. The following example uses a reserved example domain, so it is `NOT EXECUTED` as a live integration test:\\n\\n```python\\nimport requests\\n\\ntry:\\n    response = requests.get(\\n        \\\"https:\u002F\u002Fapi.example.com\u002Fitems\\\",\\n        timeout=20,\\n    )\\n    response.raise_for_status()\\n\\n    content_type = response.headers.get(\\\"content-type\\\", \\\"\\\")\\n    media_type = content_type.partition(\\\";\\\")[0].strip().lower()\\n\\n    if not (\\n        media_type == \\\"application\u002Fjson\\\"\\n        or media_type.endswith(\\\"+json\\\")\\n    ):\\n        raise ValueError(\\n            f\\\"Expected a JSON response, received \\\"\\n            f\\\"{content_type or 'no content type'}\\\"\\n        )\\n\\n    data = response.json()\\n\\nexcept requests.exceptions.Timeout:\\n    print(\\\"The request timed out.\\\")\\nexcept requests.exceptions.HTTPError as error:\\n    print(f\\\"HTTP error: {error}\\\")\\nexcept requests.exceptions.JSONDecodeError as error:\\n    print(f\\\"The response was not valid JSON: {error}\\\")\\nexcept requests.exceptions.RequestException as error:\\n    print(f\\\"Request failed: {error}\\\")\\nexcept ValueError as error:\\n    print(error)\\n```\\n\\nThe specific JSON decoding branch must appear before the broad `RequestException` branch because Requests' `JSONDecodeError` is also a `RequestException`. A JSON content type is useful evidence, but it does not guarantee that the response body contains valid JSON.\\n\\nIf this stage fails, inspect the request rather than changing the file parser. The guides to [Python requests headers](https:\u002F\u002Frola-ip.co\u002Fblog\u002Fpython-requests-headers\u002F) and [Python requests timeout](https:\u002F\u002Frola-ip.co\u002Fblog\u002Fpython-requests-timeout\u002F) cover two common network-side causes.\\n\\nSome authorized collection workflows also need requests to originate from a specific region. In that case, follow the current [Python proxy integration](https:\u002F\u002Fdoc.rola-ip.co\u002Fguide\u002Fintegration\u002Fpython.html) instructions and confirm that you have permission to access and collect the target data. Rola IP's [web scraping proxy](https:\u002F\u002Frola-ip.co\u002Fweb-scraping-use-case\u002F) page explains the relevant use case. None of these network settings changes how `json.load()` parses a local file.\\n\\n![rola-python-proxy-integration](https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F05-rola-python-proxy-integration.webp)\\n\\n## A short debugging checklist\\n\\nIf reading a JSON file still fails, check the problem in this order:\\n\\n1. Print the resolved path and confirm that the file exists.\\n2. Open it with the expected encoding, usually UTF-8.\\n3. Decide whether the input is one JSON document, a JSON string, or JSON Lines.\\n4. Run `python -m json.tool` against a standard JSON document.\\n5. Use the line and column from `JSONDecodeError` to find the first syntax problem.\\n6. Confirm whether the top-level result should be a dictionary or list.\\n7. Validate optional and required fields before using nested values.\\n8. For network responses, check the status code and content type before parsing.\\n\\n## Conclusion\\n\\nThe basic answer is only three steps: open the file, pass it to `json.load()`, and work with the returned Python object. Most failures happen around that line, not inside it. Resolve the path, encoding, input format, and file size first. Use `json.loads()` for strings and individual JSON Lines, and keep HTTP retrieval errors separate from local parsing errors.\"},{\"children\":[],\"direction\":null,\"format\":\"\",\"indent\":0,\"type\":\"paragraph\",\"version\":1}],\"direction\":null,\"format\":\"\",\"indent\":0,\"type\":\"root\",\"version\":1}}",{"items":35,"inline":15},[36,39,42,45,48,51,54,57],{"title":37,"desc":38},"What is the easiest way to read a JSON file in Python?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">Use Python's built-in \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> module with a context manager:\u003C\u002Fspan>\u003C\u002Fp>\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">import json\u003C\u002Fspan>\u003Cbr>\u003Cbr>\u003Cspan style=\"white-space: pre-wrap;\">with open(\"data.json\", encoding=\"utf-8\") as file:\u003C\u002Fspan>\u003Cbr>\u003Cspan style=\"white-space: pre-wrap;\"> data = json.load(file)\u003C\u002Fspan>\u003Cbr>\u003C\u002Fp>\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">This needs no third-party package and returns Python dictionaries, lists, strings, numbers, booleans, or \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>None\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, depending on the JSON value.\u003C\u002Fspan>\u003C\u002Fp>",{"title":40,"desc":41},"What is the difference between json.load() and json.loads()?","\u003Cp dir=\"ltr\">\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json.load()\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> reads JSON from an open file object. \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json.loads()\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> decodes JSON already held in a string, bytes, or bytearray. The final \"s\" can be remembered as \"string.\"\u003C\u002Fspan>\u003C\u002Fp>",{"title":43,"desc":44},"How do I read a JSON file into a Python dictionary?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">Call \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json.load()\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> on a file whose top-level JSON value is an object. The result will be a Python \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>dict\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">. If the file's top-level value is an array, the result will be a \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>list\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> instead.\u003C\u002Fspan>\u003C\u002Fp>",{"title":46,"desc":47},"Why do I get JSONDecodeError when the file looks correct?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">Check the reported line and column. Frequent causes are single quotes, a trailing comma, comments, an unquoted property name, multiple adjacent JSON objects, or an HTML error page saved with a \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>.json\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> extension. \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>python -m json.tool filename.json\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> can help locate standard JSON syntax errors.\u003C\u002Fspan>\u003C\u002Fp>",{"title":49,"desc":50},"How can I read a JSON file from another folder?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">Pass the full path or build it with \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>pathlib.Path\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">. If the path should be relative to the script, use \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>Path(__file__).resolve().parent \u002F \"folder\" \u002F \"data.json\"\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> rather than relying on the current working directory.\u003C\u002Fspan>\u003C\u002Fp>",{"title":52,"desc":53},"How do I read a large JSON file without running out of memory?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">For JSON Lines, iterate over the file and parse one line at a time. For a single huge array or object, use a streaming parser such as \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>ijson\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, or change the source format. Standard \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json.load()\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> creates the complete Python object in memory.\u003C\u002Fspan>\u003C\u002Fp>",{"title":55,"desc":56},"Can Python read JSON with comments or trailing commas?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">The standard \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>json\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\"> module rejects comments and trailing commas. Its default decoder is permissive in other places: it accepts \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>NaN\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>Infinity\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>-Infinity\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, and repeated object names, keeping only the last value for a repeated name. Remove comments and trailing commas, or use a parser designed for the actual format, such as JSON5, when the producer intentionally uses it.\u003C\u002Fspan>\u003C\u002Fp>",{"title":58,"desc":59},"How do I read JSON from an API in Python?","\u003Cp dir=\"ltr\">\u003Cspan style=\"white-space: pre-wrap;\">With \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>requests\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">, check the response status and content type, then call \u003C\u002Fspan>\u003Ccode spellcheck=\"false\" style=\"white-space: pre-wrap;\">\u003Cspan>response.json()\u003C\u002Fspan>\u003C\u002Fcode>\u003Cspan style=\"white-space: pre-wrap;\">. Catch network errors separately from JSON decoding errors. An API can return HTML or plain text during an error, even if successful responses are normally JSON.\u003C\u002Fspan>\u003C\u002Fp>",{"@context":61,"@type":62,"@id":63,"mainEntity":64},"https:\u002F\u002Fschema.org","FAQPage","https:\u002F\u002Frola-ip.co\u002Fblog\u002Fhow-to-read-a-json-file-in-python\u002F#faq",[65,70,73,76,79,82,85,88],{"@type":66,"name":37,"acceptedAnswer":67},"Question",{"@type":68,"text":69},"Answer","Use Python's built-in json module with a context manager: import json with open(\"data.json\", encoding=\"utf-8\") as file: data = json.load(file) This needs no third-party package and returns Python dictionaries, lists, strings, numbers, booleans, or None, depending on the JSON value.",{"@type":66,"name":40,"acceptedAnswer":71},{"@type":68,"text":72},"json.load() reads JSON from an open file object. json.loads() decodes JSON already held in a string, bytes, or bytearray. The final \"s\" can be remembered as \"string.\"",{"@type":66,"name":43,"acceptedAnswer":74},{"@type":68,"text":75},"Call json.load() on a file whose top-level JSON value is an object. The result will be a Python dict. If the file's top-level value is an array, the result will be a list instead.",{"@type":66,"name":46,"acceptedAnswer":77},{"@type":68,"text":78},"Check the reported line and column. Frequent causes are single quotes, a trailing comma, comments, an unquoted property name, multiple adjacent JSON objects, or an HTML error page saved with a .json extension. python -m json.tool filename.json can help locate standard JSON syntax errors.",{"@type":66,"name":49,"acceptedAnswer":80},{"@type":68,"text":81},"Pass the full path or build it with pathlib.Path. If the path should be relative to the script, use Path(__file__).resolve().parent \u002F \"folder\" \u002F \"data.json\" rather than relying on the current working directory.",{"@type":66,"name":52,"acceptedAnswer":83},{"@type":68,"text":84},"For JSON Lines, iterate over the file and parse one line at a time. For a single huge array or object, use a streaming parser such as ijson, or change the source format. Standard json.load() creates the complete Python object in memory.",{"@type":66,"name":55,"acceptedAnswer":86},{"@type":68,"text":87},"The standard json module rejects comments and trailing commas. Its default decoder is permissive in other places: it accepts NaN, Infinity, -Infinity, and repeated object names, keeping only the last value for a repeated name. Remove comments and trailing commas, or use a parser designed for the actual format, such as JSON5, when the producer intentionally uses it.",{"@type":66,"name":58,"acceptedAnswer":89},{"@type":68,"text":90},"With requests, check the response status and content type, then call response.json(). Catch network errors separately from JSON decoding errors. An API can return HTML or plain text during an error, even if successful responses are normally JSON.","{\"@context\":\"https:\u002F\u002Fschema.org\",\"@type\":\"FAQPage\",\"@id\":\"https:\u002F\u002Frola-ip.co\u002Fblog\u002Fhow-to-read-a-json-file-in-python\u002F#faq\",\"mainEntity\":[{\"@type\":\"Question\",\"name\":\"What is the easiest way to read a JSON file in Python?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Use Python's built-in json module with a context manager: import json with open(\\\"data.json\\\", encoding=\\\"utf-8\\\") as file: data = json.load(file) This needs no third-party package and returns Python dictionaries, lists, strings, numbers, booleans, or None, depending on the JSON value.\"}},{\"@type\":\"Question\",\"name\":\"What is the difference between json.load() and json.loads()?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"json.load() reads JSON from an open file object. json.loads() decodes JSON already held in a string, bytes, or bytearray. The final \\\"s\\\" can be remembered as \\\"string.\\\"\"}},{\"@type\":\"Question\",\"name\":\"How do I read a JSON file into a Python dictionary?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Call json.load() on a file whose top-level JSON value is an object. The result will be a Python dict. If the file's top-level value is an array, the result will be a list instead.\"}},{\"@type\":\"Question\",\"name\":\"Why do I get JSONDecodeError when the file looks correct?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Check the reported line and column. Frequent causes are single quotes, a trailing comma, comments, an unquoted property name, multiple adjacent JSON objects, or an HTML error page saved with a .json extension. python -m json.tool filename.json can help locate standard JSON syntax errors.\"}},{\"@type\":\"Question\",\"name\":\"How can I read a JSON file from another folder?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"Pass the full path or build it with pathlib.Path. If the path should be relative to the script, use Path(__file__).resolve().parent \u002F \\\"folder\\\" \u002F \\\"data.json\\\" rather than relying on the current working directory.\"}},{\"@type\":\"Question\",\"name\":\"How do I read a large JSON file without running out of memory?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"For JSON Lines, iterate over the file and parse one line at a time. For a single huge array or object, use a streaming parser such as ijson, or change the source format. Standard json.load() creates the complete Python object in memory.\"}},{\"@type\":\"Question\",\"name\":\"Can Python read JSON with comments or trailing commas?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"The standard json module rejects comments and trailing commas. Its default decoder is permissive in other places: it accepts NaN, Infinity, -Infinity, and repeated object names, keeping only the last value for a repeated name. Remove comments and trailing commas, or use a parser designed for the actual format, such as JSON5, when the producer intentionally uses it.\"}},{\"@type\":\"Question\",\"name\":\"How do I read JSON from an API in Python?\",\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"With requests, check the response status and content type, then call response.json(). Catch network errors separately from JSON decoding errors. An API can return HTML or plain text during an error, even if successful responses are normally JSON.\"}}]}",[93],"\u002Fblog\u002Fhow-to-read-a-json-file-in-python\u002F",{"prev":95,"next":106,"related":119,"popular":153,"latest":219},{"id":96,"title":97,"slug":98,"feature_image":99,"published_at":100,"twitter_title":101,"primary_tag":102,"tags":103},"6a86a34a4956c90001bed495","How to Avoid Getting Blocked While Web Scraping: 12 Practical Methods","how-to-avoid-getting-blocked-while-scraping","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002FHow-to-Avoid-Getting-Blocked-While-Scraping-article-cover-image.webp","2026-08-20T07:24:59.000Z","Avoid getting blocked while scraping",{"name":20,"slug":20},[104,105],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},{"id":107,"title":108,"slug":109,"feature_image":110,"published_at":111,"twitter_title":112,"primary_tag":113,"tags":114},"6a8680564956c90001bed434","Request Failed with Status Code 429: Axios Causes and Fixes","request-failed-with-status-code-429","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002FRequest-failed-with-status-code-429-article-cover-image.webp","2026-08-20T06:26:21.000Z","Request failed with status code 429",{"name":20,"slug":20},[115,116],{"name":20,"slug":20,"visibility":21},{"name":117,"slug":118,"visibility":21},"排障指南","troubleshooting",[120,131,142],{"id":121,"title":122,"slug":123,"feature_image":124,"published_at":125,"twitter_title":126,"primary_tag":127,"tags":128},"6b0e973a92ab700001dc0c73","Agent-Sim Proxy Setup on Linux: Routing and Exit-IP Checks","agent-sim-proxy-setup","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F12\u002FAgent-Sim-Proxy-Setup-1.webp","2026-12-01T09:54:13.000Z","Agent-Sim Proxy Setup",{"name":20,"slug":20},[129,130],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},{"id":132,"title":133,"slug":134,"feature_image":135,"published_at":136,"twitter_title":137,"primary_tag":138,"tags":139},"6b0d3e4b92ab700001dc0a73","Scrape Indeed Jobs with Python: Extract Job Fields and Export to CSV","scrape-indeed-jobs","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002FScrape-Indeed-Jobs.webp","2026-11-30T09:37:05.000Z","indeed job scraper",{"name":20,"slug":20},[140,141],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},{"id":143,"title":144,"slug":145,"feature_image":146,"published_at":147,"twitter_title":148,"primary_tag":149,"tags":150},"6b0d2bcb92ab700001dc0a12","Node.js HTTP Proxy Tutorial: Send HTTPS Requests with Rola IP and Verify the Exit IP","node-js-http-proxy","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002FNode.js-HTTP-Proxy-Tutorial_-Send-HTTPS-Requests-with-Rola-IP-and-Verify-the-Exit-IP.webp","2026-11-30T07:58:57.000Z","node js http proxy",{"name":20,"slug":20},[151,152],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},[154,169,181,193,205],{"id":155,"title":156,"slug":157,"feature_image":158,"published_at":159,"twitter_title":160,"primary_tag":161,"tags":162},"6aa1292f4956c90001bef44e","ProxySite.com Review (2026): Is It Safe? 5 Best Alternatives","proxysite-review-alternatives","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F09\u002FProxySite-Review-and--Alternatives-article-cover-image.webp","2026-09-09T10:16:50.000Z","proxysite",{"name":20,"slug":20},[163,164,167],{"name":20,"slug":20,"visibility":21},{"name":165,"slug":166,"visibility":21},"对比选型","comparisons",{"name":168,"slug":168,"visibility":21},"hot",{"id":170,"title":171,"slug":172,"feature_image":173,"published_at":174,"twitter_title":175,"primary_tag":176,"tags":177},"6a978f9a4956c90001bee8bb","BlockAway Alternatives: 6 Best Options (2026)","blockaway-alternatives","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F09\u002FBlockAway-Alternatives-article-cover-image.webp","2026-09-02T03:14:08.000Z","blockaway alternative",{"name":20,"slug":20},[178,179,180],{"name":20,"slug":20,"visibility":21},{"name":165,"slug":166,"visibility":21},{"name":168,"slug":168,"visibility":21},{"id":182,"title":183,"slug":184,"feature_image":185,"published_at":186,"twitter_title":187,"primary_tag":188,"tags":189},"6a912ce84956c90001bee35d","HTTPX vs Requests vs aiohttp: Features, Performance, and Python Use Cases","httpx-vs-requests-vs-aiohttp","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002FHTTPX-vs-Requests-vs-aiohttp-article-cover-image.webp","2026-08-28T07:27:34.000Z","httpx vs requests",{"name":20,"slug":20},[190,191,192],{"name":20,"slug":20,"visibility":21},{"name":165,"slug":166,"visibility":21},{"name":168,"slug":168,"visibility":21},{"id":194,"title":195,"slug":196,"feature_image":197,"published_at":198,"twitter_title":199,"primary_tag":200,"tags":201},"6a90fcea4956c90001bee256","8 Best Germany Proxies in 2026: Provider Comparison","best-germany-proxies","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002FBest-Germany-Proxies-article-cover-image.webp","2026-08-28T03:40:55.000Z","germany proxy",{"name":20,"slug":20},[202,203,204],{"name":20,"slug":20,"visibility":21},{"name":165,"slug":166,"visibility":21},{"name":168,"slug":168,"visibility":21},{"id":206,"title":207,"slug":208,"feature_image":209,"published_at":210,"twitter_title":211,"primary_tag":212,"tags":213},"6a8e92664956c90001beddc2","Bing Rank Tracker: Reliable Local SERP Monitoring Guide","bing-rank-tracker","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F08\u002F-------16.webp","2026-08-26T07:42:04.000Z","bing rank checker",{"name":20,"slug":20},[214,215,218],{"name":20,"slug":20,"visibility":21},{"name":216,"slug":217,"visibility":21},"应用场景","use-cases",{"name":168,"slug":168,"visibility":21},[220,231,242,255,266],{"id":221,"title":222,"slug":223,"feature_image":224,"published_at":225,"twitter_title":226,"primary_tag":227,"tags":228},"6b0e31bf92ab700001dc0ae6","Proxyium Review: Is It Safe? Pros, Cons and Alternatives","proxyium-review","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F12\u002FProxyium-Review.webp","2026-12-01T02:56:52.000Z","Proxyium proxy",{"name":20,"slug":20},[229,230],{"name":20,"slug":20,"visibility":21},{"name":165,"slug":166,"visibility":21},{"id":232,"title":233,"slug":234,"feature_image":235,"published_at":236,"twitter_title":237,"primary_tag":238,"tags":239},"6b09485d92ab700001dc0953","How to Set Up Chrome DevTools MCP for Multi-Region Geo-Testing with Residential Proxies","chrome-devtools-mcp-proxy-setup","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002Fchrome-devtools-mcp-proxy-setup.webp","2026-11-27T09:22:44.000Z","chrome-devtools-mcp proxy setup",{"name":20,"slug":20},[240,241],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},{"id":243,"title":244,"slug":245,"feature_image":246,"published_at":247,"twitter_title":248,"primary_tag":249,"tags":250},"6b0946f492ab700001dc0920","Best Rotating Proxies in 2026 7 Rotating Proxy Providers Compared","best-rotating-proxies","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002FBest-Rotating-Proxies-in-2026-7-Rotating-Proxy-Providers-Compared.webp","2026-11-27T09:07:09.000Z","best rotating proxies",{"name":20,"slug":20},[251,252],{"name":20,"slug":20,"visibility":21},{"name":253,"slug":254,"visibility":21},"排行榜","top-picks",{"id":256,"title":257,"slug":258,"feature_image":259,"published_at":260,"twitter_title":261,"primary_tag":262,"tags":263},"6b07a50492ab700001dc0603","How to Configure an NGINX Docker Reverse Proxy with Rola IP Egress","nginx-docker-reverse-proxy","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002FHow-to-Configure-an-NGINX-Docker-Reverse-Proxy-with-Rola-IP-Egress-1.webp","2026-11-26T03:21:51.000Z","nginx docker reverse proxy",{"name":20,"slug":20},[264,265],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21},{"id":267,"title":268,"slug":269,"feature_image":270,"published_at":271,"twitter_title":272,"primary_tag":273,"tags":274},"6b079b8692ab700001dc05ce","Android Proxy Settings for Mobile Network: The No-Root Guide (2026)","android-proxy-settings-mobile-network","https:\u002F\u002Frola-ip.co\u002Fstatic\u002Fcontent\u002Fimages\u002F2026\u002F11\u002FAndroid-Proxy-Settings-for-Mobile-Network_-The-No-Root-Guide--2026-.webp","2026-11-26T03:10:40.000Z","android proxy settings mobile network",{"name":20,"slug":20},[275,276],{"name":20,"slug":20,"visibility":21},{"name":29,"slug":30,"visibility":21}]