WikiPlus

FAQ: JSON Formatting and Validation Answered

JSON formatting and validation questions come up daily in developer forums, chat rooms, and code reviews. Why does my valid-looking JSON fail to parse? What is the difference between JSON and JavaScript object literals? How do I format JSON on the command line? When should I use a schema versus just parsing? This comprehensive FAQ answers the most common questions about working with JSON, organized into clear categories so you can find the answer you need quickly.

Basic JSON Rules and Common Misconceptions

Q: Is {name: 'Alice'} valid JSON? A: No. JSON requires double quotes for both keys and string values. {"name":"Alice"} is correct. {name:'Alice'} is JavaScript object literal syntax. This is the most common JSON misconception — the two formats look similar but have different rules. Q: Can I put comments in a JSON file? A: Standard JSON does not support comments. // and /* */ are JavaScript comment syntax and cause parse errors in JSON parsers. If you need comments in configuration files, use JSONC (JSON with Comments, supported by VS Code and some tools) or convert to another configuration format like YAML or TOML, which both support comments natively. Q: Is it okay to have a trailing comma in JSON? A: No. JSON does not allow trailing commas — a comma after the last item in an array or object is a syntax error. {"a":1,} and [1,2,3,] are both invalid JSON. JavaScript allows trailing commas in objects and arrays, which is why developers often write them and are surprised when JSON parsers reject them. Q: Does JSON support integers and floats separately? A: No. JSON has a single number type that covers both integers and floating-point values. The spec does not distinguish between 42 and 42.0. How these are stored and used depends on the programming language processing the JSON — some languages (Java, Go, Rust) have separate integer and float types and may behave differently. JSON itself does not guarantee that a number without a decimal point will be stored as an integer in the consuming language. Q: What is the maximum depth of nesting allowed in JSON? A: The JSON specification does not define a maximum depth. Practical limits are set by parser implementations — most parsers support thousands of levels of nesting before running out of stack space or hitting implementation limits. For real-world data, nesting deeper than ten to twenty levels is unusual and often indicates a design issue. Extremely deep nesting can cause performance issues and stack overflows in some parsers. Q: Can JSON arrays contain mixed types? A: Yes. [1,"two",true,null,{"key":"value"}] is valid JSON. Arrays can contain any mixture of types. Whether your application logic should accept mixed-type arrays is a separate question from whether it is valid JSON.

Formatting, Parsing, and Tooling Questions

Q: What does it mean to pretty-print JSON? A: Pretty-printing adds indentation and line breaks to make JSON human-readable. The content is unchanged — only whitespace is added. A single-line compact JSON object becomes a multi-line indented structure. Pretty-printing is the opposite of minification. Q: How do I format JSON on the command line? A: Use jq: echo '{"a":1}' | jq . — the dot is a jq filter that means output the whole input, formatted. Alternatively, Python's standard library works with no dependencies: echo '{"a":1}' | python3 -m json.tool. Node.js: echo '{"a":1}' | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.stringify(JSON.parse(d),null,2)))" Q: Why does JavaScript's JSON.parse return different types for the same JSON? A: JSON types map to JavaScript types predictably: JSON string to JS string, JSON number to JS number (either integer or float depending on value), JSON boolean to JS boolean, JSON null to JS null, JSON object to JS object, JSON array to JS array. The only surprise is large integers — JSON numbers that exceed JavaScript's safe integer range (above 2^53-1) lose precision when parsed. If you need exact large integer handling, use a library that supports BigInt parsing. Q: Can I format JSON with tabs instead of spaces? A: Yes. JSON.stringify(data, null, '\t') uses tab indentation in JavaScript. jq --tab . uses tabs in jq. Most formatters support configurable indentation. Tabs vs spaces is a style preference — tabs have the advantage that editors can display them at configurable widths, so different team members can view them at their preferred indentation width. Q: How do I convert an object to JSON in Python? A: json.dumps(your_object) for compact JSON. json.dumps(your_object, indent=2) for formatted JSON. json.dumps handles dictionaries, lists, strings, numbers, booleans, and None (which becomes null in JSON). Custom object types need either a custom encoder or conversion to a dictionary first.

Error Messages and Debugging Questions

Q: My JSON validator says error at line 1 but the file has many lines. What does that mean? A: The validator is likely reading the entire JSON as a single line — this happens when the JSON is minified (no newlines). The error position is still accurate as a character offset from the start of the string. To find it, count from the beginning of the file, or paste the JSON into a formatter first to add line breaks, then re-validate. Once formatted, the error will have a meaningful line number. Q: JSON.parse throws 'Unexpected end of JSON input.' What does this mean? A: The parser reached the end of the string while still expecting more content. Common causes: the string was truncated (missing the closing bracket or brace), you accidentally passed only part of the JSON string, or the string is empty. Check that the full JSON string was passed to parse(), that it starts with { or [ and ends with a matching } or ], and that it is not empty. Q: JSON.parse throws 'Unexpected token < in JSON at position 0.' What is happening? A: Position 0 means the very first character is wrong. The character < is the opening angle bracket of an HTML tag. You are parsing an HTML response instead of JSON — likely an error page, redirect, or content-type mismatch from your API. Check the response body before parsing: if it starts with <, it is HTML, not JSON. Check your API endpoint URL and authentication. Q: What does 'JSON.parse: expected property name or closing brace' mean? A: The parser expected a key name (a double-quoted string) or the end of the object (}) but found something else. Most common cause: a trailing comma before the closing brace — {"a":1,}. The parser finds , but expects either another key or }. Remove the trailing comma to fix this. Q: Why does my JSON parse fine in JavaScript but fail in Python? A: JavaScript and Python have slightly different handling of edge cases. JavaScript's JSON.parse is more permissive in some implementations. Python's json.loads is strict. Common cross-language differences: Python json.loads rejects trailing commas strictly; some JavaScript environments may not. NaN and Infinity are valid JavaScript values but not valid JSON — they may be accepted by some JavaScript parsers but not Python's. When JSON needs to work across languages, validate it against the strict JSON spec before relying on any one language's parser behavior.

JSON Schema and Advanced Validation Questions

Q: What is JSON Schema and do I need it? A: JSON Schema is a vocabulary for defining the expected structure of JSON data. It lets you specify which keys are required, what types values must be, length constraints, pattern constraints, and more. You need it when you have a JSON API or data format that must be consumed reliably by other systems. For simple scripts or one-off data processing, basic parsing is sufficient. For production APIs, stored data formats, or data shared between teams, JSON Schema provides a clear contract and enables automated validation. Q: Can JSON Schema validate business rules like 'startDate must be before endDate'? A: Simple date comparisons are possible with draft-07's if/then/else keywords combined with format validators, but complex cross-field business rules are beyond JSON Schema's purpose. JSON Schema validates structure and type constraints. Business rules that require comparing two values or checking database state should be validated in application code. Use JSON Schema for structural validation and application logic for semantic validation. Q: What is the difference between minItems and minimum in JSON Schema? A: minItems constrains the minimum length of an array — the array must have at least N elements. minimum constrains the minimum value of a number — the number must be at least N. They are for different types: minItems applies to array types, minimum applies to number types. Similarly, minLength (minimum string length) and maxLength work on string types. Q: How do I validate a JSON file against a schema from the command line? A: Several options: ajv-cli (npm install -g ajv-cli, then ajv validate -s schema.json -d data.json), jsonschema Python library (python -m jsonschema -i data.json schema.json), or the check-jsonschema tool. These tools return a non-zero exit code on validation failure, making them suitable for CI pipelines. For a quick check without installing tools, paste both the schema and data into an online JSON Schema validator. Q: Should I use JSON or YAML for configuration files? A: YAML is generally better for configuration files that humans edit frequently, because YAML supports comments, has a less verbose syntax, and is easier to write by hand. JSON is better for configuration that is generated programmatically or consumed by applications across multiple languages, because JSON support is universal and there is no ambiguity in the syntax. Many projects use YAML for developer-facing configuration (CI configs, Kubernetes manifests, application settings) and JSON for data interchange and APIs. If you choose JSON for configuration, consider JSONC for files that benefit from comments.

Frequently Asked Questions

Is JSON case-sensitive?
Yes. JSON keys and string values are case-sensitive. {"Name":"Alice"} and {"name":"Alice"} are different objects with different keys. JSON's built-in literal values — true, false, and null — must be lowercase; True, False, and NULL are invalid JSON. This case-sensitivity is particularly important in API development: an API that returns Name (capitalized) must be consumed with Name, not name. API clients that normalize key casing will not encounter this issue, but those that use keys directly must match the API's exact casing.
What is the correct way to represent a date in JSON?
JSON has no built-in date type. Dates are typically represented as strings using ISO 8601 format: "2026-05-12" for dates, "2026-05-12T14:30:00Z" for date-times with UTC timezone, or "2026-05-12T14:30:00+01:00" for date-times with a specific timezone offset. ISO 8601 is the de facto standard for date representation in JSON APIs. Avoid representing dates as Unix timestamps (numbers of seconds since epoch) unless you have a specific reason — ISO 8601 strings are human-readable and unambiguous about timezone. Document clearly whether your API uses UTC or local times.
Why does my formatted JSON show different whitespace than the original?
JSON parsers discard whitespace (unless it is inside a string value). When you format JSON by parsing it and re-serializing it, the output whitespace is generated by the formatter, not preserved from the original. The original might have used 4-space indentation; the formatter might use 2-space. Both are valid JSON representing the same data structure. If preserving the exact original whitespace matters — for example, in a diff or code review context — compare the raw JSON strings, not re-formatted versions. For data correctness, whitespace differences in JSON are always irrelevant.