├── .github └── workflows │ └── build.yml ├── package.json ├── LICENSE ├── .gitignore ├── README.md ├── spec.html └── docs └── index.html /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Render spec 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | job: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions/setup-node@v1 12 | with: 13 | node-version: '12.x' 14 | - run: npm install 15 | - run: npm run build 16 | - name: Commit changes to main repository 17 | if: github.event.repository.fork == false && ( github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master' ) 18 | uses: elstudio/actions-js-build/commit@v3 19 | with: 20 | commitMessage: "fixup: [spec] `npm run build`" 21 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "name": "proposal-json-parse-with-source", 4 | "version": "0.1.0", 5 | "description": "proposal-intl-segmenter proposal", 6 | "devDependencies": { 7 | "@tc39/ecma262-biblio": "2.1.2481", 8 | "ecmarkup": "^15.0.4" 9 | }, 10 | "scripts": { 11 | "clean": "rm -rf docs", 12 | "prebuild": "npm run clean && mkdir docs", 13 | "build": "ecmarkup --lint-spec --strict --load-biblio @tc39/ecma262-biblio spec.html docs/index.html" 14 | }, 15 | "repository": "tc39/proposal-json-parse-with-source", 16 | "author": "ECMA TC39", 17 | "license": "SEE LICENSE IN https://tc39.github.io/ecma262/#sec-copyright-and-software-license", 18 | "homepage": "https://github.com/tc39/proposal-json-parse-with-source" 19 | } 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Richard Gibson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #################################################################################################### 2 | # https://github.com/github/gitignore/blob/e5323759e387ba347a9d50f8b0ddd16502eb71d4/Node.gitignore 3 | #################################################################################################### 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | .pnpm-debug.log* 13 | 14 | # Diagnostic reports (https://nodejs.org/api/report.html) 15 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 16 | 17 | # Runtime data 18 | pids 19 | *.pid 20 | *.seed 21 | *.pid.lock 22 | 23 | # Directory for instrumented libs generated by jscoverage/JSCover 24 | lib-cov 25 | 26 | # Coverage directory used by tools like istanbul 27 | coverage 28 | *.lcov 29 | 30 | # nyc test coverage 31 | .nyc_output 32 | 33 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 34 | .grunt 35 | 36 | # Bower dependency directory (https://bower.io/) 37 | bower_components 38 | 39 | # node-waf configuration 40 | .lock-wscript 41 | 42 | # Compiled binary addons (https://nodejs.org/api/addons.html) 43 | build/Release 44 | 45 | # Dependency directories 46 | node_modules/ 47 | jspm_packages/ 48 | 49 | # Snowpack dependency directory (https://snowpack.dev/) 50 | web_modules/ 51 | 52 | # TypeScript cache 53 | *.tsbuildinfo 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Optional stylelint cache 62 | .stylelintcache 63 | 64 | # Microbundle cache 65 | .rpt2_cache/ 66 | .rts2_cache_cjs/ 67 | .rts2_cache_es/ 68 | .rts2_cache_umd/ 69 | 70 | # Optional REPL history 71 | .node_repl_history 72 | 73 | # Output of 'npm pack' 74 | *.tgz 75 | 76 | # Yarn Integrity file 77 | .yarn-integrity 78 | 79 | # dotenv environment variable files 80 | .env 81 | .env.development.local 82 | .env.test.local 83 | .env.production.local 84 | .env.local 85 | 86 | # parcel-bundler cache (https://parceljs.org/) 87 | .cache 88 | .parcel-cache 89 | 90 | # Next.js build output 91 | .next 92 | out 93 | 94 | # Nuxt.js build / generate output 95 | .nuxt 96 | dist 97 | 98 | # Gatsby files 99 | .cache/ 100 | # Comment in the public line in if your project uses Gatsby and not Next.js 101 | # https://nextjs.org/blog/next-9-1#public-directory-support 102 | # public 103 | 104 | # vuepress build output 105 | .vuepress/dist 106 | 107 | # vuepress v2.x temp and cache directory 108 | .temp 109 | .cache 110 | 111 | # Docusaurus cache and generated files 112 | .docusaurus 113 | 114 | # Serverless directories 115 | .serverless/ 116 | 117 | # FuseBox cache 118 | .fusebox/ 119 | 120 | # DynamoDB Local files 121 | .dynamodb/ 122 | 123 | # TernJS port file 124 | .tern-port 125 | 126 | # Stores VSCode versions used for testing VSCode extensions 127 | .vscode-test 128 | 129 | # yarn v2 130 | .yarn/cache 131 | .yarn/unplugged 132 | .yarn/build-state.yml 133 | .yarn/install-state.gz 134 | .pnp.* 135 | 136 | 137 | #################################################################################################### 138 | # https://github.com/tc39/template-for-proposals/blob/1a895fb15ea985fe632b04e921423b6e67ad04bb/.gitignore 139 | #################################################################################################### 140 | 141 | # Only apps should have lockfiles 142 | yarn.lock 143 | package-lock.json 144 | npm-shrinkwrap.json 145 | pnpm-lock.yaml 146 | 147 | 148 | #################################################################################################### 149 | # https://github.com/github/gitignore/blob/e5323759e387ba347a9d50f8b0ddd16502eb71d4/Global/Vim.gitignore 150 | #################################################################################################### 151 | 152 | # Swap 153 | [._]*.s[a-v][a-z] 154 | !*.svg # comment out if you don't need vector files 155 | [._]*.sw[a-p] 156 | [._]s[a-rt-v][a-z] 157 | [._]ss[a-gi-z] 158 | [._]sw[a-p] 159 | 160 | # Session 161 | Session.vim 162 | Sessionx.vim 163 | 164 | # Temporary 165 | .netrwhist 166 | *~ 167 | # Auto-generated tag files 168 | tags 169 | # Persistent undo 170 | [._]*.un~ 171 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JSON.parse source text access 2 | 3 | A proposal for extending `JSON.parse` behavior to grant reviver functions access to the input source text and extending `JSON.stringify` behavior to support object placeholders for raw JSON text primitives. 4 | 5 | [2023 September slides](https://docs.google.com/presentation/d/1pg1gnNeMIcAbwq-CdQE7vlSldlNZ5q2hC5OA-U8ScI8/edit?usp=sharing) 6 | 7 | [original 2018 September slides](https://docs.google.com/presentation/d/1PB0HCOxWZikFmTAqR5U2ZZjEiDV7NjhPN_-SK5NNG0w/edit?usp=sharing) 8 | 9 | ## Status 10 | This proposal is at stage 4 of [the TC39 Process](https://tc39.github.io/process-document/). 11 | 12 | ## Champions 13 | * Richard Gibson 14 | * Mathias Bynens 15 | 16 | ## Motivation 17 | Transformation between ECMAScript values and JSON text is lossy. 18 | This is most obvious in the case of deserializing numbers (e.g., `"999999999999999999"`, `"999999999999999999.0"`, and `"1000000000000000000"` all parse to `1000000000000000000`), but also comes up when attempting to round-tripping non-primitive values such as Date objects (e.g., `JSON.parse(JSON.stringify(new Date("2018-09-25T14:00:00Z")))` yields a string `"2018-09-25T14:00:00.000Z"`). 19 | 20 | Neither of these examples is hypothetical—serializing a [BigInt](https://github.com/tc39/proposal-bigint) as JSON is specified to throw an exception because there is no output that would round-trip through `JSON.parse`, and a similar concept has been raised regarding the [Temporal proposal](https://github.com/tc39/proposal-temporal). 21 | 22 | `JSON.parse` accepts a reviver function capable of processing inbound values, but it is invoked bottom-up and receives so little context (a _key_, an already-lossy _value_, and a receiver upon which _key_ is an own property with value _value_) that it is practically useless. 23 | We intend to remedy that. 24 | 25 | ## Proposed Solution 26 | Update `JSON.parse` to provide reviver functions with more arguments, primarily conveying the source text from which a value was derived (inclusive of punctuation but exclusive of leading/trailing insignificant whitespace). 27 | 28 | ## Serialization 29 | Although originally not included in this proposal, support for non-lossy serialization with `JSON.stringify` (and thus also complete round-trippability) was requested and added (cf. [#12](https://github.com/tc39/proposal-json-parse-with-source/issues/12)), currently using special "raw JSON" frozen objects constructible with `JSON.rawJSON` but possibly subject to change (cf. [#18](https://github.com/tc39/proposal-json-parse-with-source/issues/18) and [#19](https://github.com/tc39/proposal-json-parse-with-source/issues/19)). 30 | 31 | ## Illustrative examples 32 | ```js 33 | const digitsToBigInt = (key, val, {source}) => 34 | /^[0-9]+$/.test(source) ? BigInt(source) : val; 35 | 36 | const bigIntToRawJSON = (key, val) => 37 | typeof val === "bigint" ? JSON.rawJSON(String(val)) : val; 38 | 39 | const tooBigForNumber = BigInt(Number.MAX_SAFE_INTEGER) + 2n; 40 | JSON.parse(String(tooBigForNumber), digitsToBigInt) === tooBigForNumber; 41 | // → true 42 | 43 | const wayTooBig = BigInt("1" + "0".repeat(1000)); 44 | JSON.parse(String(wayTooBig), digitsToBigInt) === wayTooBig; 45 | // → true 46 | 47 | const embedded = JSON.stringify({ tooBigForNumber }, bigIntToRawJSON); 48 | embedded === '{"tooBigForNumber":9007199254740993}'; 49 | // → true 50 | ``` 51 | 52 | ### Potential enhancements 53 | #### Expose position and input information 54 | `String.prototype.replace` passes position and input arguments to replacer functions and the return value from `RegExp.prototype.exec` has "index" and "input" properties; `JSON.parse` could behave similarly. 55 | ```js 56 | const input = '\n\t"use\\u0020strict"'; 57 | let spied; 58 | const parsed = JSON.parse(input, (key, val, context) => (spied = context, val)); 59 | parsed === 'use strict'; 60 | // → true 61 | spied.source === '"use\\u0020strict"'; 62 | // → true 63 | spied.index === 2; 64 | // → true 65 | spied.input === input; 66 | // → true 67 | 68 | ``` 69 | 70 | #### Supply an array of keys for understanding value context 71 | A reviver function sees values bottom-up, but the data structure hierarchy is already known and can be supplied to it, with or without the phantom leading empty string. 72 | ```js 73 | const input = '{ "foo": [{ "bar": "baz" }] }'; 74 | const expectedKeys = ['foo', 0, 'bar']; 75 | let spiedKeys; 76 | JSON.parse(input, (key, val, {keys}) => (spiedKeys = spiedKeys || keys, val)); 77 | expectedKeys.length === spiedKeys.length; 78 | // → true 79 | expectedKeys.every((key, i) => spiedKeys[i] === key); 80 | // → true 81 | ``` 82 | 83 | ## Implementations 84 | * [JavaScriptCore](https://github.com/WebKit/WebKit/pull/7057) 85 | * [SpiderMonkey](https://bugzilla.mozilla.org/show_bug.cgi?id=1855468) 86 | * [V8](https://issues.chromium.org/issues/42202895) 87 | * [@ungap/raw-json](https://www.npmjs.com/package/@ungap/raw-json) 88 | 89 | ## Discussion 90 | ### Backwards Compatibility 91 | Conforming ECMAScript implementations are not permitted to extend the grammar accepted by `JSON.parse`. 92 | This proposal does not make any such attempt, and adding new function parameters is among the safest changes that can be made to the language. 93 | All input to `JSON.parse` that is currently rejected will continue to be, all input that is currently accepted will continue to be, and the only changes to its output will be directly controlled by user code. 94 | 95 | ### Modified values 96 | Reviver functions are intended to modify or remove values in the output, but those changes should have no effect on the source-derived arguments passed to them. 97 | Because reviver functions are invoked bottom-up, this means that values may not correlate with source text. 98 | We consider this to be acceptable, but mostly moot (see the following point). Where _not_ moot (such as when not-yet-visited array indexes or object entries are modified), source text is suppressed. 99 | 100 | ### Non-primitive values 101 | Per https://github.com/tc39/proposal-json-parse-with-source/issues/10#issuecomment-704441802 , source text exposure is limited to primitive values. 102 | -------------------------------------------------------------------------------- /spec.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
  5 | title: JSON.parse source text access
  6 | status: proposal
  7 | stage: 4
  8 | shortname: <a href="https://github.com/tc39/proposal-json-parse-with-source">proposal-json-parse-with-source</a>
  9 | contributors: Richard Gibson
 10 | 
11 | 38 | 39 | 40 |

The JSON Object

41 |

The JSON object:

42 | 51 |

The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used in this specification is exactly that described by ECMA-404. Conforming implementations of `JSON.parse` and `JSON.stringify` must support the exact interchange format described in the ECMA-404 specification without any deletions or extensions to the format.

52 | 53 | 54 | 55 |

JSON.isRawJSON ( _O_ )

56 |

This function performs the following steps when called:

57 | 58 | 1. If Type(_O_) is Object and _O_ has an [[IsRawJSON]] internal slot, return *true*. 59 | 1. Return *false*. 60 | 61 |
62 |
63 | 64 | 65 |

JSON.parse ( _text_ [ , _reviver_ ] )

66 |

This function parses a JSON text (a JSON-formatted String) and produces an ECMAScript language value. The JSON format represents literals, arrays, and objects with a syntax similar to the syntax for ECMAScript literals, Array Initializers, and Object Initializers. After parsing, JSON objects are realized as ECMAScript objects. JSON arrays are realized as ECMAScript Array instances. JSON strings, numbers, booleans, and null are realized as ECMAScript Strings, Numbers, Booleans, and *null*.

67 |

The optional _reviver_ parameter is a function that takes two parameters, _key_ and _value_. It can filter and transform the results. It is called with each of the _key_/_value_ pairs produced by the parse,For each value produced by the parse, it is called with three arguments (the key, the value, and a context object containing [for unmodified primitive values] details of the corresponding Parse Node) and its return value is used instead of the original value. If it returns what it received, the structure is not modified. If it returns *undefined* then the property is deleted from the result.

68 | 69 | 1. Let _jsonString_ be ? ToString(_text_). 70 | 1. [id="step-json-parse-validate"] Parse StringToCodePoints(_jsonString_) as a JSON text as specified in ECMA-404. Throw a *SyntaxError* exception if it is not a valid JSON text as defined in that specification. 71 | 1. Let _scriptString_ be the string-concatenation of *"("*, _jsonString_, and *");"*. 72 | 1. [id="step-json-parse-parse"] Let _script_ be ParseText(StringToCodePoints(_scriptString_), |Script|). 73 | 1. NOTE: The early error rules defined in have special handling for the above invocation of ParseText. 74 | 1. Assert: _script_ is a Parse Node. 75 | 1. [id="step-json-parse-eval"] Let _completion_ be Completion(Evaluation of _script_). 76 | 1. NOTE: The PropertyDefinitionEvaluation semantics defined in have special handling for the above evaluation. 77 | 1. Let _unfiltered_ be _completion_.[[Value]]. 78 | 1. [id="step-json-parse-assert-type"] Assert: _unfiltered_ is either a String, Number, Boolean, Null, or an Object that is defined by either an |ArrayLiteral| or an |ObjectLiteral|. 79 | 1. If IsCallable(_reviver_) is *true*, then 80 | 1. Let _root_ be OrdinaryObjectCreate(%Object.prototype%). 81 | 1. Let _rootName_ be the empty String. 82 | 1. Perform ! CreateDataPropertyOrThrow(_root_, _rootName_, _unfiltered_). 83 | 1. Let _snapshot_ be CreateJSONParseRecord(_script_, _rootName_, _unfiltered_). 84 | 1. Return ? InternalizeJSONProperty(_root_, _rootName_, _reviver_, _snapshot_). 85 | 1. Else, 86 | 1. Return _unfiltered_. 87 | 88 |

The *"length"* property of the `parse` function is *2*𝔽.

89 | 90 |

Valid JSON text is a subset of the ECMAScript |PrimaryExpression| syntax. Step verifies that _jsonString_ conforms to that subset, and step asserts that that parsing and evaluation returns a value of an appropriate type.

91 |

However, because behaves differently during `JSON.parse`, the same source text can produce different results when evaluated as a |PrimaryExpression| rather than as JSON. Furthermore, the Early Error for duplicate *"__proto__"* properties in object literals, which likewise does not apply during `JSON.parse`, means that not all texts accepted by `JSON.parse` are valid as a |PrimaryExpression|, despite matching the grammar.

92 |
93 | 94 | 95 | 96 |

JSON Parse Record

97 |

A JSON Parse Record is a Record value used to describe the initial state of a value parsed from JSON text.

98 |

JSON Parse Records have the fields listed in .

99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 |
Field NameValueMeaning
[[ParseNode]]a Parse NodeThe context Parse Node.
[[Key]]a property nameThe property name with which [[Value]] is associated.
[[Value]]an ECMAScript language valueThe value produced by evaluation of [[ParseNode]].
[[Elements]]a List of JSON Parse RecordsJSON Parse Records corresponding with the elements of a [[Value]] that is an Array, in order. If [[Value]] is not an Array, the List will be empty.
[[Entries]]a List of JSON Parse RecordsJSON Parse Records corresponding with the entries of a [[Value]] that is a non-Array Object, in source order. If [[Value]] is not a non-Array Object, the List will be empty.
132 |
133 |
134 | 135 | 136 |

137 | CreateJSONParseRecord ( 138 | _parseNode_: a Parse Node, 139 | _key_: a property name, 140 | _val_: an ECMAScript language value, 141 | ): a JSON Parse Record 142 |

143 |
144 |
description
145 |
It recursively combines a _parseNode_ parsed from JSON text and the _val_ produced by its evaluation.
146 |
147 | 148 | 1. Let _typedValNode_ be ShallowestContainedJSONValue of _parseNode_. 149 | 1. Assert: _typedValNode_ is not ~empty~. 150 | 1. Let _elements_ be a new empty List. 151 | 1. Let _entries_ be a new empty List. 152 | 1. If _val_ is an Object, then 153 | 1. Let _isArray_ be ! IsArray(_val_). 154 | 1. If _isArray_ is *true*, then 155 | 1. Assert: _typedValNode_ is an |ArrayLiteral| Parse Node. 156 | 1. Let _contentNodes_ be ArrayLiteralContentNodes of _typedValNode_. 157 | 1. Let _len_ be the number of elements in _contentNodes_. 158 | 1. Let _valLen_ be ! LengthOfArrayLike(_val_). 159 | 1. Assert: _valLen_ = _len_. 160 | 1. Let _I_ be 0. 161 | 1. Repeat, while _I_ < _len_, 162 | 1. Let _propName_ be ! ToString(𝔽(_I_)). 163 | 1. Let _elementParseRecord_ be CreateJSONParseRecord(_contentNodes_[_I_], _propName_, ! Get(_val_, _propName_)). 164 | 1. Append _elementParseRecord_ to _elements_. 165 | 1. Set _I_ to _I_ + 1. 166 | 1. Else, 167 | 1. Assert: _typedValNode_ is an |ObjectLiteral| Parse Node. 168 | 1. Let _propertyNodes_ be PropertyDefinitionNodes of _typedValNode_. 169 | 1. NOTE: Because _val_ was produced from JSON text and has not been modified, all of its property keys are Strings and will be exhaustively enumerated in source text order. 170 | 1. Let _keys_ be ! EnumerableOwnProperties(_val_, ~key~). 171 | 1. For each String _P_ of _keys_, do 172 | 1. NOTE: In the case of JSON text specifying multiple name/value pairs with the same name for a single object (such as {"a":"lost","a":"kept"}), the value for the corresponding property of the resulting ECMAScript object is specified by the last pair with that name. 173 | 1. Let _propertyDefinition_ be ~empty~. 174 | 1. For each Parse Node _propertyNode_ of _propertyNodes_, do 175 | 1. Let _propName_ be PropName of _propertyNode_. 176 | 1. If SameValue(_propName_, _P_) is *true*, set _propertyDefinition_ to _propertyNode_. 177 | 1. Assert: _propertyDefinition_ is PropertyDefinition : PropertyName `:` AssignmentExpression. 178 | 1. Let _propertyValueNode_ be the |AssignmentExpression| of _propertyDefinition_. 179 | 1. Let _entryParseRecord_ be CreateJSONParseRecord(_propertyValueNode_, _P_, ! Get(_val_, _P_)). 180 | 1. Append _entryParseRecord_ to _entries_. 181 | 1. Else, 182 | 1. Assert: _typedValNode_ is not an |ArrayLiteral| Parse Node and not an |ObjectLiteral| Parse Node. 183 | 1. Return the JSON Parse Record { [[ParseNode]]: _typedValNode_, [[Key]]: _key_, [[Value]]: _val_, [[Elements]]: _elements_, [[Entries]]: _entries_ }. 184 | 185 |
186 |
187 | 188 | 189 |

190 | InternalizeJSONProperty ( 191 | _holder_: an Object, 192 | _name_: a String, 193 | _reviver_: a function object, 194 | _parseRecord_: either a JSON Parse Record or ~empty~, 195 | ): either a normal completion containing an ECMAScript language value or a throw completion 196 |

197 |
198 |
199 | 200 |

This algorithm intentionally does not throw an exception if either [[Delete]] or CreateDataProperty return *false*.

201 |
202 |

It performs the following steps when called:

203 | 204 | 1. Let _val_ be ? Get(_holder_, _name_). 205 | 1. Let _context_ be OrdinaryObjectCreate(%Object.prototype%). 206 | 1. If _parseRecord_ is a JSON Parse Record and SameValue(_parseRecord_.[[Value]], _val_) is *true*, then 207 | 1. If _val_ is not an Object, then 208 | 1. Let _parseNode_ be _parseRecord_.[[ParseNode]]. 209 | 1. Assert: _parseNode_ is not an |ArrayLiteral| Parse Node and not an |ObjectLiteral| Parse Node. 210 | 1. Let _sourceText_ be the source text matched by _parseNode_. 211 | 1. Perform ! CreateDataPropertyOrThrow(_context_, *"source"*, CodePointsToString(_sourceText_)). 212 | 1. Let _elementRecords_ be _parseRecord_.[[Elements]]. 213 | 1. Let _entryRecords_ be _parseRecord_.[[Entries]]. 214 | 1. Else, 215 | 1. Let _elementRecords_ be a new empty List. 216 | 1. Let _entryRecords_ be a new empty List. 217 | 1. If _val_ is an Object, then 218 | 1. Let _isArray_ be ? IsArray(_val_). 219 | 1. If _isArray_ is *true*, then 220 | 1. Let _elementRecordsLen_ be the number of elements in _elementRecords_. 221 | 1. Let _len_ be ? LengthOfArrayLike(_val_). 222 | 1. Let _I_ be 0. 223 | 1. Repeat, while _I_ < _len_, 224 | 1. Let _prop_ be ! ToString(𝔽(_I_)). 225 | 1. If _I_ < _elementRecordsLen_, let _elementRecord_ be _elementRecords_[_I_]. Otherwise, let _elementRecord_ be ~empty~. 226 | 1. Let _newElement_ be ? InternalizeJSONProperty(_val_, _prop_, _reviver_, _elementRecord_). 227 | 1. If _newElement_ is *undefined*, then 228 | 1. Perform ? _val_.[[Delete]](_prop_). 229 | 1. Else, 230 | 1. Perform ? CreateDataProperty(_val_, _prop_, _newElement_). 231 | 1. Set _I_ to _I_ + 1. 232 | 1. Else, 233 | 1. Let _keys_ be ? EnumerableOwnProperties(_val_, ~key~). 234 | 1. For each String _P_ of _keys_, do 235 | 1. Let _entryRecord_ be the element of _entryRecords_ whose [[Key]] field is _P_. If there is no such element, let _entryRecord_ be ~empty~. 236 | 1. Let _newElement_ be ? InternalizeJSONProperty(_val_, _P_, _reviver_, _entryRecord_). 237 | 1. If _newElement_ is *undefined*, then 238 | 1. Perform ? _val_.[[Delete]](_P_). 239 | 1. Else, 240 | 1. Perform ? CreateDataProperty(_val_, _P_, _newElement_). 241 | 1. Return ? Call(_reviver_, _holder_, « _name_, _val_, _context_ »). 242 | 243 |

It is not permitted for a conforming implementation of `JSON.parse` to extend the JSON grammars. If an implementation wishes to support a modified or extended JSON interchange format it must do so by defining a different parse function.

244 | 245 |

In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.

246 |
247 |
248 | 249 | 250 | 251 |

252 | Static Semantics: ShallowestContainedJSONValue ( ): a Parse Node or ~empty~ 253 |

254 |
255 |
description
256 |
It performs a breadth-first search of the parse tree rooted at the context node, and returns the first node that is an instance of a nonterminal corresponding to a JSON value, or ~empty~ if there is no such node.
257 |
258 | 259 | 1. Let _F_ be the active function object. 260 | 1. Assert: _F_ is a `JSON.parse` built-in function object (see JSON.parse). 261 | 1. Let _types_ be « |NullLiteral|, |BooleanLiteral|, |NumericLiteral|, |StringLiteral|, |ArrayLiteral|, |ObjectLiteral|, |UnaryExpression| ». 262 | 1. Let _unaryExpression_ be ~empty~. 263 | 1. Let _queue_ be « this Parse Node ». 264 | 1. Repeat, while _queue_ is not empty, 265 | 1. Let _candidate_ be the first element of _queue_. 266 | 1. Remove the first element from _queue_. 267 | 1. Let _queuedChildren_ be *false*. 268 | 1. For each nonterminal _type_ of _types_, do 269 | 1. If _candidate_ is an instance of _type_, then 270 | 1. NOTE: In the JSON grammar, a number token may represent a negative value. In ECMAScript, negation is represented as a unary operation. 271 | 1. If _type_ is |UnaryExpression|, then 272 | 1. Set _unaryExpression_ to _candidate_. 273 | 1. Else if _type_ is |NumericLiteral|, then 274 | 1. Assert: _candidate_ is contained within _unaryExpression_. 275 | 1. Return _unaryExpression_. 276 | 1. Else, 277 | 1. Return _candidate_. 278 | 1. If _queuedChildren_ is *false* and _candidate_ is an instance of a nonterminal and _candidate_ Contains _type_ is *true*, then 279 | 1. Let _children_ be a List containing each child node of _candidate_, in order. 280 | 1. Set _queue_ to the list-concatenation of _queue_ and _children_. 281 | 1. Set _queuedChildren_ to *true*. 282 | 1. Return ~empty~. 283 | 284 | 285 |

286 | It may make sense to generalize this operation and define Contains in terms of it rather than vice versa, but Contains is currently limited to a single target nonterminal and has specialized treatment for e.g. |ClassTail| descending into |ClassBody| exclusively to inspect computed names. 287 |

288 |
289 |
290 |
291 |
292 | 293 | 294 | 295 |

JSON.rawJSON ( _text_ )

296 |

The `rawJSON` function returns an object representing raw JSON text of a string, number, boolean, or null value.

297 | 298 | 1. Let _jsonString_ be ? ToString(_text_). 299 | 1. Throw a *SyntaxError* exception if _jsonString_ is the empty String, or if either the first or last code unit of _jsonString_ is any of 0x0009 (CHARACTER TABULATION), 0x000A (LINE FEED), 0x000D (CARRIAGE RETURN), or 0x0020 (SPACE). 300 | 1. Parse StringToCodePoints(_jsonString_) as a JSON text as specified in ECMA-404. Throw a *SyntaxError* exception if it is not a valid JSON text as defined in that specification, or if its outermost value is an object or array as defined in that specification. 301 | 1. Let _internalSlotsList_ be « [[IsRawJSON]] ». 302 | 1. Let _obj_ be OrdinaryObjectCreate(*null*, _internalSlotsList_). 303 | 1. Perform ! CreateDataPropertyOrThrow(_obj_, *"rawJSON"*, _jsonString_). 304 | 1. Perform ! SetIntegrityLevel(_obj_, ~frozen~). 305 | 1. Return _obj_. 306 | 307 |
308 |
309 | 310 | 311 |

JSON.stringify ( _value_ [ , _replacer_ [ , _space_ ] ] )

312 |

The `stringify` function returns a String in UTF-16 encoded JSON format representing an ECMAScript language value, or *undefined*. It can take three parameters. The _value_ parameter is an ECMAScript language value, which is usually an object or array, although it can also be a String, Boolean, Number or *null*. The optional _replacer_ parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as an inclusion list for selecting the object properties that will be stringified. The optional _space_ parameter is a String or Number that allows the result to have white space injected into it to improve human readability.

313 | 314 | 315 |

316 | SerializeJSONProperty ( 317 | _state_: a JSON Serialization Record, 318 | _key_: a String, 319 | _holder_: an Object, 320 | ): either a normal completion containing either *undefined* or a String, or a throw completion 321 |

322 |
323 |
324 | 325 | 1. Let _value_ be ? Get(_holder_, _key_). 326 | 1. If _value_ is an Object or _value_ is a BigInt, then 327 | 1. Let _toJSON_ be ? GetV(_value_, *"toJSON"*). 328 | 1. If IsCallable(_toJSON_) is *true*, then 329 | 1. Set _value_ to ? Call(_toJSON_, _value_, « _key_ »). 330 | 1. If _state_.[[ReplacerFunction]] is not *undefined*, then 331 | 1. Set _value_ to ? Call(_state_.[[ReplacerFunction]], _holder_, « _key_, _value_ »). 332 | 1. If _value_ is an Object, then 333 | 1. If _value_ has an [[IsRawJSON]] internal slot, then 334 | 1. Return ! Get(_value_, *"rawJSON"*). 335 | 1. If _value_ has a [[NumberData]] internal slot, then 336 | 1. Set _value_ to ? ToNumber(_value_). 337 | 1. Else if _value_ has a [[StringData]] internal slot, then 338 | 1. Set _value_ to ? ToString(_value_). 339 | 1. Else if _value_ has a [[BooleanData]] internal slot, then 340 | 1. Set _value_ to _value_.[[BooleanData]]. 341 | 1. Else if _value_ has a [[BigIntData]] internal slot, then 342 | 1. Set _value_ to _value_.[[BigIntData]]. 343 | 1. If _value_ is *null*, return *"null"*. 344 | 1. If _value_ is *true*, return *"true"*. 345 | 1. If _value_ is *false*, return *"false"*. 346 | 1. If _value_ is a String, return QuoteJSONString(_value_). 347 | 1. If _value_ is a Number, then 348 | 1. If _value_ is finite, return ! ToString(_value_). 349 | 1. Return *"null"*. 350 | 1. If _value_ is a BigInt, throw a *TypeError* exception. 351 | 1. If _value_ is an Object and IsCallable(_value_) is *false*, then 352 | 1. Let _isArray_ be ? IsArray(_value_). 353 | 1. If _isArray_ is *true*, return ? SerializeJSONArray(_state_, _value_). 354 | 1. Return ? SerializeJSONObject(_state_, _value_). 355 | 1. Return *undefined*. 356 | 357 |
358 |
359 |
360 | 361 | 362 | 363 |

364 | Static Semantics: ArrayLiteralContentNodes ( 365 | ): a List of Parse Nodes 366 |

367 |
368 |
369 | 370 | 371 | ArrayLiteral : 372 | `[` Elision? `]` 373 | `[` ElementList `]` 374 | `[` ElementList `,` Elision? `]` 375 | 376 | 377 | 1. Let _elements_ be a new empty List. 378 | 1. If |ElementList| is present, set _elements_ to the list-concatenation of _elements_ and ArrayLiteralContentNodes of |ElementList|. 379 | 1. If |Elision| is present, append |Elision| to _elements_. 380 | 1. Return _elements_. 381 | 382 | 383 | ElementList : Elision? AssignmentExpression 384 | 385 | 1. Let _elements_ be a new empty List. 386 | 1. If |Elision| is present, append |Elision| to _elements_. 387 | 1. Return the list-concatenation of _elements_ and « |AssignmentExpression| ». 388 | 389 | 390 | ElementList : Elision? SpreadElement 391 | 392 | 1. Let _elements_ be a new empty List. 393 | 1. If |Elision| is present, append |Elision| to _elements_. 394 | 1. Return the list-concatenation of _elements_ and « |SpreadElement| ». 395 | 396 | 397 | ElementList : ElementList `,` Elision? AssignmentExpression 398 | 399 | 1. Let _elements_ be ArrayLiteralContentNodes of |ElementList|. 400 | 1. If |Elision| is present, append |Elision| to _elements_. 401 | 1. Return the list-concatenation of _elements_ and « |AssignmentExpression| ». 402 | 403 | 404 | ElementList : ElementList `,` Elision? SpreadElement 405 | 406 | 1. Let _elements_ be ArrayLiteralContentNodes of |ElementList|. 407 | 1. If |Elision| is present, append |Elision| to _elements_. 408 | 1. Return the list-concatenation of _elements_ and « |SpreadElement| ». 409 | 410 |
411 |
412 | 413 | 414 | 415 |

416 | Static Semantics: PropertyDefinitionNodes ( 417 | ): a List of Parse Nodes 418 |

419 |
420 |
421 | 422 | ObjectLiteral : `{` `}` 423 | 424 | 1. Return a new empty List. 425 | 426 | 427 | PropertyDefinitionList : PropertyDefinition 428 | 429 | 1. Return « |PropertyDefinition| ». 430 | 431 | 432 | PropertyDefinitionList : PropertyDefinitionList `,` PropertyDefinition 433 | 434 | 1. Return the list-concatenation of PropertyDefinitionNodes of |PropertyDefinitionList| and « |PropertyDefinition| ». 435 | 436 |
437 |
438 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | JSON.parse source text access
2518 |

Proposal proposal-json-parse-with-source

Stage 4 Draft / November 23, 2025

JSON.parse source text access

2527 | 2554 | 2555 | 2556 |

1 The JSON Object

2557 |

The JSON object:

2558 | 2567 |

The JSON Data Interchange Format is defined in ECMA-404. The JSON interchange format used in this specification is exactly that described by ECMA-404. Conforming implementations of JSON.parse and JSON.stringify must support the exact interchange format described in the ECMA-404 specification without any deletions or extensions to the format.

2568 | 2569 | 2570 | 2571 |

1.1 JSON.isRawJSON ( O )

2572 |

This function performs the following steps when called:

2573 |
  1. If Type(O) is Object and O has an [[IsRawJSON]] internal slot, return true.
  2. Return false.
2574 |
2575 |
2576 | 2577 | 2578 |

1.2 JSON.parse ( text [ , reviver ] )

2579 |

This function parses a JSON text (a JSON-formatted String) and produces an ECMAScript language value. The JSON format represents literals, arrays, and objects with a syntax similar to the syntax for ECMAScript literals, Array Initializers, and Object Initializers. After parsing, JSON objects are realized as ECMAScript objects. JSON arrays are realized as ECMAScript Array instances. JSON strings, numbers, booleans, and null are realized as ECMAScript Strings, Numbers, Booleans, and null.

2580 |

The optional reviver parameter is a function that takes two parameters, key and value. It can filter and transform the results. It is called with each of the key/value pairs produced by the parse,For each value produced by the parse, it is called with three arguments (the key, the value, and a context object containing [for unmodified primitive values] details of the corresponding Parse Node) and its return value is used instead of the original value. If it returns what it received, the structure is not modified. If it returns undefined then the property is deleted from the result.

2581 |
  1. Let jsonString be ? ToString(text).
  2. Parse StringToCodePoints(jsonString) as a JSON text as specified in ECMA-404. Throw a SyntaxError exception if it is not a valid JSON text as defined in that specification.
  3. Let scriptString be the string-concatenation of "(", jsonString, and ");".
  4. Let script be ParseText(StringToCodePoints(scriptString), Script).
  5. NOTE: The early error rules defined in 13.2.5.1 have special handling for the above invocation of ParseText.
  6. Assert: script is a Parse Node.
  7. Let completion be Completion(Evaluation of script).
  8. NOTE: The PropertyDefinitionEvaluation semantics defined in 13.2.5.5 have special handling for the above evaluation.
  9. Let unfiltered be completion.[[Value]].
  10. Assert: unfiltered is either a String, Number, Boolean, Null, or an Object that is defined by either an ArrayLiteral or an ObjectLiteral.
  11. If IsCallable(reviver) is true, then
    1. Let root be OrdinaryObjectCreate(%Object.prototype%).
    2. Let rootName be the empty String.
    3. Perform ! CreateDataPropertyOrThrow(root, rootName, unfiltered).
    4. Let snapshot be CreateJSONParseRecord(script, rootName, unfiltered).
    5. Return ? InternalizeJSONProperty(root, rootName, reviver, snapshot).
  12. Else,
    1. Return unfiltered.
2582 |

The "length" property of the parse function is 2𝔽.

2583 | Note
2584 |

Valid JSON text is a subset of the ECMAScript PrimaryExpression syntax. Step 2 verifies that jsonString conforms to that subset, and step 10 asserts that that parsing and evaluation returns a value of an appropriate type.

2585 |

However, because 13.2.5.5 behaves differently during JSON.parse, the same source text can produce different results when evaluated as a PrimaryExpression rather than as JSON. Furthermore, the Early Error for duplicate "__proto__" properties in object literals, which likewise does not apply during JSON.parse, means that not all texts accepted by JSON.parse are valid as a PrimaryExpression, despite matching the grammar.

2586 |
2587 | 2588 | 2589 | 2590 |

1.2.1 JSON Parse Record

2591 |

A JSON Parse Record is a Record value used to describe the initial state of a value parsed from JSON text.

2592 |

JSON Parse Records have the fields listed in Table 1.

2593 |
Table 1: JSON Parse Record Fields
2594 | 2595 | 2596 | 2597 | 2598 | 2599 | 2600 | 2601 | 2602 | 2603 | 2604 | 2605 | 2606 | 2607 | 2608 | 2609 | 2610 | 2611 | 2612 | 2613 | 2614 | 2615 | 2616 | 2617 | 2618 | 2619 | 2620 | 2621 | 2622 | 2623 | 2624 | 2625 |
Field NameValueMeaning
[[ParseNode]]a Parse NodeThe context Parse Node.
[[Key]]a property nameThe property name with which [[Value]] is associated.
[[Value]]an ECMAScript language valueThe value produced by evaluation of [[ParseNode]].
[[Elements]]a List of JSON Parse RecordsJSON Parse Records corresponding with the elements of a [[Value]] that is an Array, in order. If [[Value]] is not an Array, the List will be empty.
[[Entries]]a List of JSON Parse RecordsJSON Parse Records corresponding with the entries of a [[Value]] that is a non-Array Object, in source order. If [[Value]] is not a non-Array Object, the List will be empty.
2626 |
2627 |
2628 | 2629 | 2630 |

1.2.2 CreateJSONParseRecord ( parseNode, key, val )

2631 |

The abstract operation CreateJSONParseRecord takes arguments parseNode (a Parse Node), key (a property name), and val (an ECMAScript language value) and returns a JSON Parse Record. It recursively combines a parseNode parsed from JSON text and the val produced by its evaluation. It performs the following steps when called:

2632 |
  1. Let typedValNode be ShallowestContainedJSONValue of parseNode.
  2. Assert: typedValNode is not empty.
  3. Let elements be a new empty List.
  4. Let entries be a new empty List.
  5. If val is an Object, then
    1. Let isArray be ! IsArray(val).
    2. If isArray is true, then
      1. Assert: typedValNode is an ArrayLiteral Parse Node.
      2. Let contentNodes be ArrayLiteralContentNodes of typedValNode.
      3. Let len be the number of elements in contentNodes.
      4. Let valLen be ! LengthOfArrayLike(val).
      5. Assert: valLen = len.
      6. Let I be 0.
      7. Repeat, while I < len,
        1. Let propName be ! ToString(𝔽(I)).
        2. Let elementParseRecord be CreateJSONParseRecord(contentNodes[I], propName, ! Get(val, propName)).
        3. Append elementParseRecord to elements.
        4. Set I to I + 1.
    3. Else,
      1. Assert: typedValNode is an ObjectLiteral Parse Node.
      2. Let propertyNodes be PropertyDefinitionNodes of typedValNode.
      3. NOTE: Because val was produced from JSON text and has not been modified, all of its property keys are Strings and will be exhaustively enumerated in source text order.
      4. Let keys be ! EnumerableOwnProperties(val, key).
      5. For each String P of keys, do
        1. NOTE: In the case of JSON text specifying multiple name/value pairs with the same name for a single object (such as {"a":"lost","a":"kept"}), the value for the corresponding property of the resulting ECMAScript object is specified by the last pair with that name.
        2. Let propertyDefinition be empty.
        3. For each Parse Node propertyNode of propertyNodes, do
          1. Let propName be PropName of propertyNode.
          2. If SameValue(propName, P) is true, set propertyDefinition to propertyNode.
        4. Assert: propertyDefinition is 2633 | PropertyDefinition : 2634 | PropertyName 2635 | : 2636 | AssignmentExpression 2637 | 2638 | 2639 | .
        5. Let propertyValueNode be the AssignmentExpression of propertyDefinition.
        6. Let entryParseRecord be CreateJSONParseRecord(propertyValueNode, P, ! Get(val, P)).
        7. Append entryParseRecord to entries.
  6. Else,
    1. Assert: typedValNode is not an ArrayLiteral Parse Node and not an ObjectLiteral Parse Node.
  7. Return the JSON Parse Record { [[ParseNode]]: typedValNode, [[Key]]: key, [[Value]]: val, [[Elements]]: elements, [[Entries]]: entries }.
2640 |
2641 |
2642 | 2643 | 2644 |

1.2.3 InternalizeJSONProperty ( holder, name, reviver, parseRecord )

2645 |

The abstract operation InternalizeJSONProperty takes arguments holder (an Object), name (a String), reviver (a function object), and parseRecord (either a JSON Parse Record or empty) and returns either a normal completion containing an ECMAScript language value or a throw completion.

2646 | Note 1
2647 |

This algorithm intentionally does not throw an exception if either [[Delete]] or CreateDataProperty return false.

2648 |
2649 |

It performs the following steps when called:

2650 |
  1. Let val be ? Get(holder, name).
  2. Let context be OrdinaryObjectCreate(%Object.prototype%).
  3. If parseRecord is a JSON Parse Record and SameValue(parseRecord.[[Value]], val) is true, then
    1. If val is not an Object, then
      1. Let parseNode be parseRecord.[[ParseNode]].
      2. Assert: parseNode is not an ArrayLiteral Parse Node and not an ObjectLiteral Parse Node.
      3. Let sourceText be the source text matched by parseNode.
      4. Perform ! CreateDataPropertyOrThrow(context, "source", CodePointsToString(sourceText)).
    2. Let elementRecords be parseRecord.[[Elements]].
    3. Let entryRecords be parseRecord.[[Entries]].
  4. Else,
    1. Let elementRecords be a new empty List.
    2. Let entryRecords be a new empty List.
  5. If val is an Object, then
    1. Let isArray be ? IsArray(val).
    2. If isArray is true, then
      1. Let elementRecordsLen be the number of elements in elementRecords.
      2. Let len be ? LengthOfArrayLike(val).
      3. Let I be 0.
      4. Repeat, while I < len,
        1. Let prop be ! ToString(𝔽(I)).
        2. If I < elementRecordsLen, let elementRecord be elementRecords[I]. Otherwise, let elementRecord be empty.
        3. Let newElement be ? InternalizeJSONProperty(val, prop, reviver, elementRecord).
        4. If newElement is undefined, then
          1. Perform ? val.[[Delete]](prop).
        5. Else,
          1. Perform ? CreateDataProperty(val, prop, newElement).
        6. Set I to I + 1.
    3. Else,
      1. Let keys be ? EnumerableOwnProperties(val, key).
      2. For each String P of keys, do
        1. Let entryRecord be the element of entryRecords whose [[Key]] field is P. If there is no such element, let entryRecord be empty.
        2. Let newElement be ? InternalizeJSONProperty(val, P, reviver, entryRecord).
        3. If newElement is undefined, then
          1. Perform ? val.[[Delete]](P).
        4. Else,
          1. Perform ? CreateDataProperty(val, P, newElement).
  6. Return ? Call(reviver, holder, « name, val, context »).
2651 |

It is not permitted for a conforming implementation of JSON.parse to extend the JSON grammars. If an implementation wishes to support a modified or extended JSON interchange format it must do so by defining a different parse function.

2652 | Note 2
2653 |

In the case where there are duplicate name Strings within an object, lexically preceding values for the same key shall be overwritten.

2654 |
2655 |
2656 | 2657 | 2658 | 2659 |

1.2.4 Static Semantics: ShallowestContainedJSONValue

2660 |

The syntax-directed operation ShallowestContainedJSONValue takes no arguments and returns a Parse Node or empty. It performs a breadth-first search of the parse tree rooted at the context node, and returns the first node that is an instance of a nonterminal corresponding to a JSON value, or empty if there is no such node.

2661 |
  1. Let F be the active function object.
  2. Assert: F is a JSON.parse built-in function object (see JSON.parse).
  3. Let types be « NullLiteral, BooleanLiteral, NumericLiteral, StringLiteral, ArrayLiteral, ObjectLiteral, UnaryExpression ».
  4. Let unaryExpression be empty.
  5. Let queue be « this Parse Node ».
  6. Repeat, while queue is not empty,
    1. Let candidate be the first element of queue.
    2. Remove the first element from queue.
    3. Let queuedChildren be false.
    4. For each nonterminal type of types, do
      1. If candidate is an instance of type, then
        1. NOTE: In the JSON grammar, a number token may represent a negative value. In ECMAScript, negation is represented as a unary operation.
        2. If type is UnaryExpression, then
          1. Set unaryExpression to candidate.
        3. Else if type is NumericLiteral, then
          1. Assert: candidate is contained within unaryExpression.
          2. Return unaryExpression.
        4. Else,
          1. Return candidate.
      2. If queuedChildren is false and candidate is an instance of a nonterminal and candidate Contains type is true, then
        1. Let children be a List containing each child node of candidate, in order.
        2. Set queue to the list-concatenation of queue and children.
        3. Set queuedChildren to true.
  7. Return empty.
2662 | Editor's Note
2663 |

2664 | It may make sense to generalize this operation and define Contains in terms of it rather than vice versa, but Contains is currently limited to a single target nonterminal and has specialized treatment for e.g. ClassTail descending into ClassBody exclusively to inspect computed names. 2665 |

2666 |
2667 |
2668 |
2669 |
2670 | 2671 | 2672 | 2673 |

1.3 JSON.rawJSON ( text )

2674 |

The rawJSON function returns an object representing raw JSON text of a string, number, boolean, or null value.

2675 |
  1. Let jsonString be ? ToString(text).
  2. Throw a SyntaxError exception if jsonString is the empty String, or if either the first or last code unit of jsonString is any of 0x0009 (CHARACTER TABULATION), 0x000A (LINE FEED), 0x000D (CARRIAGE RETURN), or 0x0020 (SPACE).
  3. Parse StringToCodePoints(jsonString) as a JSON text as specified in ECMA-404. Throw a SyntaxError exception if it is not a valid JSON text as defined in that specification, or if its outermost value is an object or array as defined in that specification.
  4. Let internalSlotsList be « [[IsRawJSON]] ».
  5. Let obj be OrdinaryObjectCreate(null, internalSlotsList).
  6. Perform ! CreateDataPropertyOrThrow(obj, "rawJSON", jsonString).
  7. Perform ! SetIntegrityLevel(obj, frozen).
  8. Return obj.
2676 |
2677 |
2678 | 2679 | 2680 |

1.4 JSON.stringify ( value [ , replacer [ , space ] ] )

2681 |

The stringify function returns a String in UTF-16 encoded JSON format representing an ECMAScript language value, or undefined. It can take three parameters. The value parameter is an ECMAScript language value, which is usually an object or array, although it can also be a String, Boolean, Number or null. The optional replacer parameter is either a function that alters the way objects and arrays are stringified, or an array of Strings and Numbers that acts as an inclusion list for selecting the object properties that will be stringified. The optional space parameter is a String or Number that allows the result to have white space injected into it to improve human readability.

2682 | 2683 | 2684 |

1.4.1 SerializeJSONProperty ( state, key, holder )

2685 |

The abstract operation SerializeJSONProperty takes arguments state (a JSON Serialization Record), key (a String), and holder (an Object) and returns either a normal completion containing either undefined or a String, or a throw completion. It performs the following steps when called:

2686 |
  1. Let value be ? Get(holder, key).
  2. If value is an Object or value is a BigInt, then
    1. Let toJSON be ? GetV(value, "toJSON").
    2. If IsCallable(toJSON) is true, then
      1. Set value to ? Call(toJSON, value, « key »).
  3. If state.[[ReplacerFunction]] is not undefined, then
    1. Set value to ? Call(state.[[ReplacerFunction]], holder, « key, value »).
  4. If value is an Object, then
    1. If value has an [[IsRawJSON]] internal slot, then
      1. Return ! Get(value, "rawJSON").
    2. If value has a [[NumberData]] internal slot, then
      1. Set value to ? ToNumber(value).
    3. Else if value has a [[StringData]] internal slot, then
      1. Set value to ? ToString(value).
    4. Else if value has a [[BooleanData]] internal slot, then
      1. Set value to value.[[BooleanData]].
    5. Else if value has a [[BigIntData]] internal slot, then
      1. Set value to value.[[BigIntData]].
  5. If value is null, return "null".
  6. If value is true, return "true".
  7. If value is false, return "false".
  8. If value is a String, return QuoteJSONString(value).
  9. If value is a Number, then
    1. If value is finite, return ! ToString(value).
    2. Return "null".
  10. If value is a BigInt, throw a TypeError exception.
  11. If value is an Object and IsCallable(value) is false, then
    1. Let isArray be ? IsArray(value).
    2. If isArray is true, return ? SerializeJSONArray(state, value).
    3. Return ? SerializeJSONObject(state, value).
  12. Return undefined.
2687 |
2688 |
2689 |
2690 | 2691 | 2692 | 2693 |

2 Static Semantics: ArrayLiteralContentNodes

2694 |

The syntax-directed operation ArrayLiteralContentNodes takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

2695 | 2696 | 2697 | ArrayLiteral : 2698 | [ 2699 | Elisionopt 2700 | ] 2701 | 2702 | 2703 | [ 2704 | ElementList 2705 | ] 2706 | 2707 | 2708 | [ 2709 | ElementList 2710 | , 2711 | Elisionopt 2712 | ] 2713 | 2714 | 2715 | 2716 |
  1. Let elements be a new empty List.
  2. If ElementList is present, set elements to the list-concatenation of elements and ArrayLiteralContentNodes of ElementList.
  3. If Elision is present, append Elision to elements.
  4. Return elements.
2717 | 2718 | 2719 | ElementList : 2720 | Elisionopt 2721 | AssignmentExpression 2722 | 2723 | 2724 | 2725 |
  1. Let elements be a new empty List.
  2. If Elision is present, append Elision to elements.
  3. Return the list-concatenation of elements and « AssignmentExpression ».
2726 | 2727 | 2728 | ElementList : 2729 | Elisionopt 2730 | SpreadElement 2731 | 2732 | 2733 | 2734 |
  1. Let elements be a new empty List.
  2. If Elision is present, append Elision to elements.
  3. Return the list-concatenation of elements and « SpreadElement ».
2735 | 2736 | 2737 | ElementList : 2738 | ElementList 2739 | , 2740 | Elisionopt 2741 | AssignmentExpression 2742 | 2743 | 2744 | 2745 |
  1. Let elements be ArrayLiteralContentNodes of ElementList.
  2. If Elision is present, append Elision to elements.
  3. Return the list-concatenation of elements and « AssignmentExpression ».
2746 | 2747 | 2748 | ElementList : 2749 | ElementList 2750 | , 2751 | Elisionopt 2752 | SpreadElement 2753 | 2754 | 2755 | 2756 |
  1. Let elements be ArrayLiteralContentNodes of ElementList.
  2. If Elision is present, append Elision to elements.
  3. Return the list-concatenation of elements and « SpreadElement ».
2757 |
2758 |
2759 | 2760 | 2761 | 2762 |

3 Static Semantics: PropertyDefinitionNodes

2763 |

The syntax-directed operation PropertyDefinitionNodes takes no arguments and returns a List of Parse Nodes. It is defined piecewise over the following productions:

2764 | 2765 | 2766 | ObjectLiteral : 2767 | { 2768 | } 2769 | 2770 | 2771 | 2772 |
  1. Return a new empty List.
2773 | 2774 | 2775 | PropertyDefinitionList : PropertyDefinition 2776 | 2777 | 2778 |
  1. Return « PropertyDefinition ».
2779 | 2780 | 2781 | PropertyDefinitionList : 2782 | PropertyDefinitionList 2783 | , 2784 | PropertyDefinition 2785 | 2786 | 2787 | 2788 |
  1. Return the list-concatenation of PropertyDefinitionNodes of PropertyDefinitionList and « PropertyDefinition ».
2789 |
2790 |

A Copyright & Software License

2791 | 2792 |

Copyright Notice

2793 |

© 2025 Richard Gibson

2794 | 2795 |

Software License

2796 |

All Software contained in this document ("Software") is protected by copyright and is being made available under the "BSD License", included below. This Software may be subject to third party rights (rights from parties other than Ecma International), including patent rights, and no licenses under such third party rights are granted under this license even if the third party concerned is a member of Ecma International. SEE THE ECMA CODE OF CONDUCT IN PATENT MATTERS AVAILABLE AT https://ecma-international.org/memento/codeofconduct.htm FOR INFORMATION REGARDING THE LICENSING OF PATENT CLAIMS THAT ARE REQUIRED TO IMPLEMENT ECMA INTERNATIONAL STANDARDS.

2797 | 2798 |

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

2799 | 2800 |
    2801 |
  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  2. 2802 |
  3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  4. 2803 |
  5. Neither the name of the authors nor Ecma International may be used to endorse or promote products derived from this software without specific prior written permission.
  6. 2804 |
2805 | 2806 |

THIS SOFTWARE IS PROVIDED BY THE ECMA INTERNATIONAL "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ECMA INTERNATIONAL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

2807 | 2808 |
2809 |
2810 |
--------------------------------------------------------------------------------