How to Fix JSON Single Quotes: The Complete Guide
JSON single quote errors crash parsers in every language. Learn exactly why JSON rejects single quotes, how to fix them in Python and JavaScript, and how to use an online tool for instant repair.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →Single-quoted JSON breaks every parser — Python's json.loads, JavaScript's JSON.parse, and every API client on the planet. The fix is straightforward once you understand the rule, and this guide walks through every scenario: why it happens, how to fix it in code, and how to use an online tool when you just need a quick repair.
Why JSON Rejects Single Quotes
JSON is defined by RFC 8259, which requires all strings — both keys and values — to be wrapped in double quotes only. Single quotes are simply not part of the JSON specification.
This means the following is invalid JSON, even though it looks like it should work:
// INVALID — single quotes on keys and values
{'name': 'Alice', 'age': 30}
The valid form is:
// VALID
{"name": "Alice", "age": 30}
There is no parser setting or "loose mode" that accepts single-quoted JSON. The spec is absolute.
What Causes the Single Quote Error
The most common sources of single-quoted JSON are:
Python dictionary literals. When you callstr() on a Python dict or use an f-string to embed it, Python prints it with single quotes. This output is NOT valid JSON.
data = {"name": "Alice", "city": "London"}
print(str(data))
Output: {'name': 'Alice', 'city': 'London'} ← NOT valid JSON
Shell commands and echo output. Copying output from a terminal where single quotes were used for quoting.
LLM and AI output. Language models sometimes generate Python-dict-style output instead of strict JSON, especially when prompted loosely.
Manual editing. Developers who write JSON by hand sometimes use single quotes by habit from JavaScript or Python experience.
Third-party APIs. Some non-standard APIs return single-quoted responses, particularly older PHP and Python services.
How to Fix JSON Single Quotes in Python
Option 1 — Use json.dumps() instead of str()
The correct way to convert a Python dict to JSON is json.dumps(), which always produces valid double-quoted JSON:
import json
data = {"name": "Alice", "age": 30}
Wrong — produces single-quoted Python dict representation
bad = str(data)
Correct — produces valid JSON
good = json.dumps(data)
print(good)
Output: {"name": "Alice", "age": 30}
Option 2 — Replace single quotes in a broken string
If you've received a single-quoted string from an external source and need to repair it, a simple replace works for basic cases:
import json
broken = "{'name': 'Alice', 'age': 30}"
Simple fix for basic cases (no apostrophes in values)
fixed = broken.replace("'", '"')
data = json.loads(fixed)
print(data)
Output: {'name': 'Alice', 'age': 30}
Warning: This naive approach breaks if your values contain apostrophes (e.g., {'message': "it's broken"}). For those cases, use ast.literal_eval:
Option 3 — ast.literal_eval for Python dict strings
If the string is specifically Python dict syntax (not arbitrary JSON), ast.literal_eval is the most reliable repair:
import ast
import json
broken = "{'name': \"it's Alice\", 'city': 'London'}"
ast.literal_eval handles Python dict syntax safely
data = ast.literal_eval(broken)
Now convert to real JSON
valid_json = json.dumps(data)
print(valid_json)
Output: {"name": "it's Alice", "city": "London"}
ast.literal_eval understands Python's quoting rules and produces a real dict, which you can then serialize to proper JSON with json.dumps.
Option 4 — Use the json-repair library
For production pipelines where JSON comes from LLMs or unreliable sources, the json-repair library handles single quotes and many other malformations automatically:
from json_repair import repair_json
broken = "{'name': 'Alice', 'scores': [95, 87, 91]}"
fixed = repair_json(broken)
print(fixed)
Output: {"name": "Alice", "scores": [95, 87, 91]}
Install it with:
pip install json-repair
How to Fix JSON Single Quotes in JavaScript
Option 1 — Never use single quotes when building JSON
If you're constructing JSON manually in JavaScript, use JSON.stringify() instead:
const data = { name: "Alice", age: 30 };
const validJson = JSON.stringify(data);
console.log(validJson);
// Output: {"name":"Alice","age":30}
Option 2 — Replace single quotes for basic strings
For simple cases without apostrophes in values:
const broken = "{'name': 'Alice', 'age': 30}";
const fixed = broken.replace(/'/g, '"');
const data = JSON.parse(fixed);
console.log(data);
// Output: { name: 'Alice', age: 30 }
Option 3 — A robust replacement with regex
When values may contain apostrophes, a more careful regex avoids replacing apostrophes inside words:
function fixSingleQuoteJson(str) {
// Replace single-quoted keys
return str
.replace(/([{,]\s)'([^']+?)'\s:/g, '$1"$2":')
// Replace single-quoted string values
.replace(/:\s'([^'])'/g, ': "$1"');
}
const broken = "{'name': 'Alice', 'active': true}";
const fixed = fixSingleQuoteJson(broken);
const data = JSON.parse(fixed);
console.log(data);
For complex cases with nested quotes, use a dedicated library or the online tool below.
Fix JSON Single Quotes Online — No Code Required
If you have a one-off snippet to fix and don't want to write code, aijsonmedic.com repairs single-quoted JSON instantly in your browser.
Paste your broken JSON → it detects single quotes, trailing commas, unquoted keys, and other errors → returns clean, valid JSON you can copy immediately.
The tool also works on:
- JSON from LLM and AI output
- Python dict strings
- JSON with trailing commas or comments
- Mixed-quote JSON
Try the JSON formatter if you also need to pretty-print the result, or use JSON validator to confirm your output is spec-compliant before sending it to an API. The JSON Studio combines repair, format, validate, and diff in a single workspace — useful when you need to do more than one operation on the same broken JSON.
For reference on all JSON data types and syntax rules, see the JSON glossary.
Quick Reference — Single Quote Fix by Language
| Language | Best Fix |
|---|---|
| Python (dict to JSON) | json.dumps(data) |
| Python (string from LLM) | ast.literal_eval() then json.dumps() |
| Python (production pipeline) | json-repair library |
| JavaScript (constructing) | JSON.stringify(obj) |
| JavaScript (string repair) | Regex replace or online tool |
| Any language (ad hoc) | aijsonmedic.com |
Why You Can't Just Use eval()
A common suggestion online is to use eval() in JavaScript or Python to parse single-quoted JSON:
// NEVER do this
const data = eval("({'name': 'Alice'})");
This executes arbitrary code. If the string came from user input or an external API, this is a critical security vulnerability. Use ast.literal_eval in Python (which only evaluates literals, not arbitrary code) or a proper parser.
Exact Error Messages by Language
Knowing the exact error message helps confirm the single-quote issue before you start debugging:
Pythonjson.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
The column 2 (char 1) tells you the parser choked on the very first character — the opening ' of a key.
SyntaxError: Unexpected token ''' in JSON at position 0
or in newer V8 versions:
SyntaxError: Expected property name or '}' in JSON at position 1
Ruby
JSON::ParserError: 765: unexpected token at '{'name': 'Alice'}'
Java (Jackson)
com.fasterxml.jackson.core.JsonParseException: Unexpected character (''' (code 39)): was expecting double-quote to start field name
Go (encoding/json)
invalid character '\'' looking for beginning of object key string
jq
parse error (Invalid numeric literal at line 1, column 8): {'name': 'Alice'}
All of these mean the same thing: the parser found a single quote where only a double quote is valid.
Fixing Single Quotes in TypeScript
TypeScript uses the same JSON.parse under the hood, so the fix strategies are identical to JavaScript — but typed wrappers make it safer:
import { repairJson } from 'jsonrepair'; // npm install jsonrepair
function safeParseJson<T>(input: string): T {
try {
return JSON.parse(input) as T;
} catch {
// Attempt repair before giving up
const repaired = repairJson(input);
return JSON.parse(repaired) as T;
}
}
interface User {
name: string;
age: number;
}
const broken = "{'name': 'Alice', 'age': 30}";
const user = safeParseJson<User>(broken);
console.log(user.name); // Alice
For production TypeScript pipelines, pair this with Zod for runtime validation after repair:
import { z } from 'zod';
import { repairJson } from 'jsonrepair';
const UserSchema = z.object({ name: z.string(), age: z.number() });
function parseAndValidate(raw: string) {
const repaired = repairJson(raw);
return UserSchema.parse(JSON.parse(repaired));
}
LLM and AI Model JSON Single Quote Issues (2026)
Single quotes from AI output are more common than they should be. The root cause: LLMs are trained on Python and JavaScript code where single quotes are valid string delimiters. Without schema enforcement, models default to the quoting style that dominated their training data.
The most reliable fix: use your provider's structured output mode.# OpenAI — enforces valid JSON schema, zero single-quote risk
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Return user data as JSON"}],
response_format={"type": "json_object"}, # Forces valid JSON
)
data = response.choices[0].message.content # Always double-quoted
Anthropic — use tool use for schema-enforced JSON
response = client.messages.create(
model="claude-opus-4-6",
tools=[{
"name": "extract_user",
"input_schema": {
"type": "object",
"properties": {"name": {"type": "string"}, "age": {"type": "integer"}},
"required": ["name", "age"]
}
}],
tool_choice={"type": "tool", "name": "extract_user"},
messages=[{"role": "user", "content": "Extract: Alice, age 30"}]
)
tool_input = response.content[0].input # Already a dict, no parsing needed
When you can't use structured output (local models, older APIs, or providers without schema enforcement), a repair layer is the next best option:
from json_repair import repair_json
import json
llm_output = "{'name': 'Alice', 'scores': [95, 87], 'active': True}"
repair_json handles single quotes, Python booleans (True/False), and more
repaired = repair_json(llm_output)
data = json.loads(repaired)
{"name": "Alice", "scores": [95, 87], "active": true}
Note: LLM outputs often combine single quotes with other issues (Python-style True/False/None instead of JSON true/false/null, trailing commas, markdown code fences). The json-repair library and the JSON repair tool handle all of these in one pass.
Frequently Asked Questions
Why does JSON not allow single quotes?The JSON specification (RFC 8259) was designed for simplicity and unambiguous parsing. Double quotes were chosen as the single string delimiter — there is no ambiguity about whether a quote character is opening or closing a string. Single quotes are not part of the spec and never have been.
Can I configure my JSON parser to accept single quotes?Standard parsers (Python's json, JavaScript's JSON.parse, Java's Jackson, etc.) follow the spec strictly and have no "lenient" mode for single quotes. Some libraries like hjson or json5 accept relaxed JSON and can handle single quotes, but their output must be converted to standard JSON before most APIs will accept it.
A naive single-quote replace will corrupt strings with apostrophes. Use ast.literal_eval in Python, a careful regex in JavaScript, or the AI JSONMedic JSON repair tool which understands the JSON structure and only replaces quotes in the right positions.
No. In valid JSON, \' is not a recognized escape sequence. The only characters that need escaping inside a double-quoted JSON string are " (as \"), \ (as \\), and control characters.
No. The JSON specification requires double quotes for both keys and string values. Single quotes are valid in JavaScript object literals but not in JSON. Any JSON parser (json.loads(), JSON.parse(), jq) will throw an error on single-quoted strings.
AI models are trained on vast amounts of Python and JavaScript code, which both allow single quotes for strings. Without strict formatting constraints, models default to single quotes. Add "Use only double quotes in JSON output" to your system prompt, or use your provider's native structured output mode to enforce valid JSON at the schema level.
What is the fastest way to fix single quotes in JSON?For simple cases with no apostrophes in values: content.replace(/'/g, '"') in JavaScript or s.replace("'", '"') in Python. For robust handling that avoids corrupting strings with apostrophes, use a repair library: from json_repair import repair_json in Python, or jsonrepair in JavaScript. The online tool works for one-off fixes without any code.
Yes — ast.literal_eval() evaluates Python literals (strings, dicts, lists, booleans, None) safely. It handles single quotes natively. But it won't handle JSON-specific values like null (Python uses None), and it requires valid Python literal syntax — not arbitrary JSON. It's the right tool when the source is a Python dict printed with str() or repr().
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles