Utility Coder
← Back to Blog
Data10 min read

JSON5 and JSONPath: Advanced JSON Techniques

Master JSON5 for human-friendly configs and JSONPath for querying JSON data. Complete guide with examples.

By Andy Pham

JSON5 and JSONPath: Advanced JSON Techniques

JSON5 extends JSON for human-friendliness, while JSONPath queries JSON like XPath queries XML.

JSON5: Human-Friendly JSON

What JSON5 Adds

{
  // Comments are allowed!
  name: 'John',  // Single quotes work
  age: 30,       // Trailing commas allowed

  /* Multi-line
     comments too */

  'hyphen-key': 'value',  // Quoted keys when needed

  // Unquoted keys
  firstName: "Jane",

  // Multi-line strings
  bio: 'This is a long string',

  // Numbers
  hex: 0xFF,
  infinity: Infinity,
  nan: NaN,
}

JSON5 vs JSON

Feature JSON JSON5
Comments No Yes
Trailing commas No Yes
Single quotes No Yes
Unquoted keys No Yes
Hex numbers No Yes
Infinity/NaN No Yes

Using JSON5

const JSON5 = require('json5');

// Parse
const data = JSON5.parse(`{
  // Config file
  name: 'app',
  version: '1.0',
}`);

// Stringify
const json5 = JSON5.stringify(data, null, 2);

JSONPath: Querying JSON

JSONPath Syntax

Expression Description
$ Root object
. Child operator
.. Recursive descent
* Wildcard
[] Subscript operator
[,] Union operator
[start:end:step] Array slice
?() Filter expression
@ Current node

Examples

{
  "store": {
    "books": [
      { "title": "Book 1", "price": 10 },
      { "title": "Book 2", "price": 20 },
      { "title": "Book 3", "price": 15 }
    ],
    "name": "My Store"
  }
}
Query Result
$.store.name "My Store"
$.store.books[0] First book
$.store.books[*].title All titles
$.store.books[?(@.price<15)] Books under $15
$..price All prices

JavaScript JSONPath

const jp = require('jsonpath');

const data = { store: { books: [...] } };

// Query
const titles = jp.query(data, '$.store.books[*].title');
const cheap = jp.query(data, '$.store.books[?(@.price<15)]');

// Get paths
const paths = jp.paths(data, '$..price');

Use Cases

JSON5

  • Configuration files
  • Development settings
  • Human-edited files
  • Comments in data

JSONPath

  • API response filtering
  • Data extraction
  • Testing assertions
  • Log analysis

Try Our Tools

Conclusion

JSON5 makes JSON configs human-friendly, while JSONPath enables powerful data querying. Both extend JSON's capabilities for real-world use cases.

Share this article