JSON.isRawJSON()
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
TheJSON.isRawJSON()
static method tests whether a value is an object returned byJSON.rawJSON()
.
Syntax
JSON.isRawJSON(value)
Parameters
value
The value to test.
Return value
true
ifvalue
is created byJSON.rawJSON()
; otherwise,false
.
Description
"Raw JSON" objects, when serialized to JSON, are treated as if they are already a piece of JSON. Furthermore, because of the wayJSON.rawJSON()
works, the raw JSON is guaranteed to be syntactically valid JSON. For more information on the shape and behavior of raw JSON objects, seeJSON.rawJSON()
. This method exists to allow other serialization libraries to implement similar behavior toJSON.stringify()
for raw JSON objects.
Examples
Using JSON.isRawJSON()
The following example demonstrates how to useJSON.isRawJSON()
to test whether an object was returned byJSON.rawJSON()
. It implements a custom serializer that serializes data to a YAML-like format.
function mySerializer(value, indent = "") { if (typeof value !== "object" || value === null) { return JSON.stringify(value); } if (JSON.isRawJSON(value)) { return value.rawJSON; } const subIndent = `${indent} `; if (Array.isArray(value)) { return `- ${value.map((v) => mySerializer(v, subIndent)).join(`\n${indent}- `)}`; } return Object.entries(value) .map(([key, value]) => { const subValue = mySerializer(value, subIndent); if (subValue.includes("\n")) { return `${key}:\n${subIndent}${subValue}`; } return `${key}: ${subValue}`; }) .join(`\n${indent}`);}console.log( mySerializer({ name: "Josh", userId: JSON.rawJSON("12345678901234567890"), friends: [ { name: "Alice", userId: JSON.rawJSON("9876543210987654321") }, { name: "Bob", userId: JSON.rawJSON("56789012345678901234") }, ], }),);// name: "Josh"// userId: 12345678901234567890// friends:// - name: "Alice"// userId: 9876543210987654321// - name: "Bob"// userId: 56789012345678901234
If in the above example, theuserId
values were not created byJSON.rawJSON()
, but passed as numbers directly, then we will get loss of precision upfront because of JS floating point precision limitations.
console.log( mySerializer({ name: "Josh", userId: 12345678901234567890, friends: [ { name: "Alice", userId: 9876543210987654321 }, { name: "Bob", userId: 56789012345678901234 }, ], }),);// name: "Josh"// userId: 12345678901234567000// friends:// - name: "Alice"// userId: 9876543210987655000// - name: "Bob"// userId: 56789012345678900000
Specifications
Specification |
---|
JSON.parse source text access # sec-json.israwjson |