You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

282 lines
10 KiB

3 months ago
  1. # JSON5 – JSON for Humans
  2. [![Build Status](https://app.travis-ci.com/json5/json5.svg?branch=main)][Build
  3. Status] [![Coverage
  4. Status](https://coveralls.io/repos/github/json5/json5/badge.svg)][Coverage
  5. Status]
  6. JSON5 is an extension to the popular [JSON] file format that aims to be
  7. easier to **write and maintain _by hand_ (e.g. for config files)**.
  8. It is _not intended_ to be used for machine-to-machine communication.
  9. (Keep using JSON or other file formats for that. 🙂)
  10. JSON5 was started in 2012, and as of 2022, now gets **[>65M downloads/week](https://www.npmjs.com/package/json5)**,
  11. ranks in the **[top 0.1%](https://gist.github.com/anvaka/8e8fa57c7ee1350e3491)** of the most depended-upon packages on npm,
  12. and has been adopted by major projects like
  13. **[Chromium](https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5;drc=5de823b36e68fd99009a29281b17bc3a1d6b329c),
  14. [Next.js](https://github.com/vercel/next.js/blob/b88f20c90bf4659b8ad5cb2a27956005eac2c7e8/packages/next/lib/find-config.ts#L43-L46),
  15. [Babel](https://babeljs.io/docs/en/config-files#supported-file-extensions),
  16. [Retool](https://community.retool.com/t/i-am-attempting-to-append-several-text-fields-to-a-google-sheet-but-receiving-a-json5-invalid-character-error/7626),
  17. [WebStorm](https://www.jetbrains.com/help/webstorm/json.html),
  18. and [more](https://github.com/json5/json5/wiki/In-the-Wild)**.
  19. It's also natively supported on **[Apple platforms](https://developer.apple.com/documentation/foundation/jsondecoder/3766916-allowsjson5)**
  20. like **MacOS** and **iOS**.
  21. Formally, the **[JSON5 Data Interchange Format](https://spec.json5.org/)** is a superset of JSON
  22. (so valid JSON files will always be valid JSON5 files)
  23. that expands its syntax to include some productions from [ECMAScript 5.1] (ES5).
  24. It's also a strict _subset_ of ES5, so valid JSON5 files will always be valid ES5.
  25. This JavaScript library is a reference implementation for JSON5 parsing and serialization,
  26. and is directly used in many of the popular projects mentioned above
  27. (where e.g. extreme performance isn't necessary),
  28. but others have created [many other libraries](https://github.com/json5/json5/wiki/In-the-Wild)
  29. across many other platforms.
  30. [Build Status]: https://app.travis-ci.com/json5/json5
  31. [Coverage Status]: https://coveralls.io/github/json5/json5
  32. [JSON]: https://tools.ietf.org/html/rfc7159
  33. [ECMAScript 5.1]: https://www.ecma-international.org/ecma-262/5.1/
  34. ## Summary of Features
  35. The following ECMAScript 5.1 features, which are not supported in JSON, have
  36. been extended to JSON5.
  37. ### Objects
  38. - Object keys may be an ECMAScript 5.1 _[IdentifierName]_.
  39. - Objects may have a single trailing comma.
  40. ### Arrays
  41. - Arrays may have a single trailing comma.
  42. ### Strings
  43. - Strings may be single quoted.
  44. - Strings may span multiple lines by escaping new line characters.
  45. - Strings may include character escapes.
  46. ### Numbers
  47. - Numbers may be hexadecimal.
  48. - Numbers may have a leading or trailing decimal point.
  49. - Numbers may be [IEEE 754] positive infinity, negative infinity, and NaN.
  50. - Numbers may begin with an explicit plus sign.
  51. ### Comments
  52. - Single and multi-line comments are allowed.
  53. ### White Space
  54. - Additional white space characters are allowed.
  55. [IdentifierName]: https://www.ecma-international.org/ecma-262/5.1/#sec-7.6
  56. [IEEE 754]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933
  57. ## Example
  58. Kitchen-sink example:
  59. ```js
  60. {
  61. // comments
  62. unquoted: 'and you can quote me on that',
  63. singleQuotes: 'I can use "double quotes" here',
  64. lineBreaks: "Look, Mom! \
  65. No \\n's!",
  66. hexadecimal: 0xdecaf,
  67. leadingDecimalPoint: .8675309, andTrailing: 8675309.,
  68. positiveSign: +1,
  69. trailingComma: 'in objects', andIn: ['arrays',],
  70. "backwardsCompatible": "with JSON",
  71. }
  72. ```
  73. A more real-world example is [this config file](https://github.com/chromium/chromium/blob/feb3c9f670515edf9a88f185301cbd7794ee3e52/third_party/blink/renderer/platform/runtime_enabled_features.json5)
  74. from the Chromium/Blink project.
  75. ## Specification
  76. For a detailed explanation of the JSON5 format, please read the [official
  77. specification](https://json5.github.io/json5-spec/).
  78. ## Installation and Usage
  79. ### Node.js
  80. ```sh
  81. npm install json5
  82. ```
  83. #### CommonJS
  84. ```js
  85. const JSON5 = require('json5')
  86. ```
  87. #### Modules
  88. ```js
  89. import JSON5 from 'json5'
  90. ```
  91. ### Browsers
  92. #### UMD
  93. ```html
  94. <!-- This will create a global `JSON5` variable. -->
  95. <script src="https://unpkg.com/json5@2/dist/index.min.js"></script>
  96. ```
  97. #### Modules
  98. ```html
  99. <script type="module">
  100. import JSON5 from 'https://unpkg.com/json5@2/dist/index.min.mjs'
  101. </script>
  102. ```
  103. ## API
  104. The JSON5 API is compatible with the [JSON API].
  105. [JSON API]:
  106. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
  107. ### JSON5.parse()
  108. Parses a JSON5 string, constructing the JavaScript value or object described by
  109. the string. An optional reviver function can be provided to perform a
  110. transformation on the resulting object before it is returned.
  111. #### Syntax
  112. JSON5.parse(text[, reviver])
  113. #### Parameters
  114. - `text`: The string to parse as JSON5.
  115. - `reviver`: If a function, this prescribes how the value originally produced by
  116. parsing is transformed, before being returned.
  117. #### Return value
  118. The object corresponding to the given JSON5 text.
  119. ### JSON5.stringify()
  120. Converts a JavaScript value to a JSON5 string, optionally replacing values if a
  121. replacer function is specified, or optionally including only the specified
  122. properties if a replacer array is specified.
  123. #### Syntax
  124. JSON5.stringify(value[, replacer[, space]])
  125. JSON5.stringify(value[, options])
  126. #### Parameters
  127. - `value`: The value to convert to a JSON5 string.
  128. - `replacer`: A function that alters the behavior of the stringification
  129. process, or an array of String and Number objects that serve as a whitelist
  130. for selecting/filtering the properties of the value object to be included in
  131. the JSON5 string. If this value is null or not provided, all properties of the
  132. object are included in the resulting JSON5 string.
  133. - `space`: A String or Number object that's used to insert white space into the
  134. output JSON5 string for readability purposes. If this is a Number, it
  135. indicates the number of space characters to use as white space; this number is
  136. capped at 10 (if it is greater, the value is just 10). Values less than 1
  137. indicate that no space should be used. If this is a String, the string (or the
  138. first 10 characters of the string, if it's longer than that) is used as white
  139. space. If this parameter is not provided (or is null), no white space is used.
  140. If white space is used, trailing commas will be used in objects and arrays.
  141. - `options`: An object with the following properties:
  142. - `replacer`: Same as the `replacer` parameter.
  143. - `space`: Same as the `space` parameter.
  144. - `quote`: A String representing the quote character to use when serializing
  145. strings.
  146. #### Return value
  147. A JSON5 string representing the value.
  148. ### Node.js `require()` JSON5 files
  149. When using Node.js, you can `require()` JSON5 files by adding the following
  150. statement.
  151. ```js
  152. require('json5/lib/register')
  153. ```
  154. Then you can load a JSON5 file with a Node.js `require()` statement. For
  155. example:
  156. ```js
  157. const config = require('./config.json5')
  158. ```
  159. ## CLI
  160. Since JSON is more widely used than JSON5, this package includes a CLI for
  161. converting JSON5 to JSON and for validating the syntax of JSON5 documents.
  162. ### Installation
  163. ```sh
  164. npm install --global json5
  165. ```
  166. ### Usage
  167. ```sh
  168. json5 [options] <file>
  169. ```
  170. If `<file>` is not provided, then STDIN is used.
  171. #### Options:
  172. - `-s`, `--space`: The number of spaces to indent or `t` for tabs
  173. - `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT
  174. - `-v`, `--validate`: Validate JSON5 but do not output JSON
  175. - `-V`, `--version`: Output the version number
  176. - `-h`, `--help`: Output usage information
  177. ## Contributing
  178. ### Development
  179. ```sh
  180. git clone https://github.com/json5/json5
  181. cd json5
  182. npm install
  183. ```
  184. When contributing code, please write relevant tests and run `npm test` and `npm
  185. run lint` before submitting pull requests. Please use an editor that supports
  186. [EditorConfig](http://editorconfig.org/).
  187. ### Issues
  188. To report bugs or request features regarding the JSON5 **data format**,
  189. please submit an issue to the official
  190. **[_specification_ repository](https://github.com/json5/json5-spec)**.
  191. Note that we will never add any features that make JSON5 incompatible with ES5;
  192. that compatibility is a fundamental premise of JSON5.
  193. To report bugs or request features regarding this **JavaScript implementation**
  194. of JSON5, please submit an issue to **_this_ repository**.
  195. ### Security Vulnerabilities and Disclosures
  196. To report a security vulnerability, please follow the follow the guidelines
  197. described in our [security policy](./SECURITY.md).
  198. ## License
  199. MIT. See [LICENSE.md](./LICENSE.md) for details.
  200. ## Credits
  201. [Aseem Kishore](https://github.com/aseemk) founded this project.
  202. He wrote a [blog post](https://aseemk.substack.com/p/ignore-the-f-ing-haters-json5)
  203. about the journey and lessons learned 10 years in.
  204. [Michael Bolin](http://bolinfest.com/) independently arrived at and published
  205. some of these same ideas with awesome explanations and detail. Recommended
  206. reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html)
  207. [Douglas Crockford](http://www.crockford.com/) of course designed and built
  208. JSON, but his state machine diagrams on the [JSON website](http://json.org/), as
  209. cheesy as it may sound, gave us motivation and confidence that building a new
  210. parser to implement these ideas was within reach! The original
  211. implementation of JSON5 was also modeled directly off of Doug’s open-source
  212. [json_parse.js] parser. We’re grateful for that clean and well-documented
  213. code.
  214. [json_parse.js]:
  215. https://github.com/douglascrockford/JSON-js/blob/03157639c7a7cddd2e9f032537f346f1a87c0f6d/json_parse.js
  216. [Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific
  217. supporter, contributing multiple patches and ideas.
  218. [Andrew Eisenberg](https://github.com/aeisenberg) contributed the original
  219. `stringify` method.
  220. [Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely
  221. with ES5, wrote the official JSON5 specification, completely rewrote the
  222. codebase from the ground up, and is actively maintaining this project.