JSON.rawJSON()
The JSON.rawJSON() static method in JavaScript is used to create a RawJSON object from a string. This object ensures that the provided string is serialized as-is when converting to JSON, without additional escaping or processing.
This method is not available in Chrome and Edge, but not in Firefox, Safari, etc.
Syntax
JSON.rawJSON(string)
Parameters
| Parameter | Description |
|---|---|
string | A valid JSON string to be treated as raw JSON. The string will be serialized as-is during JSON serialization. |
Return Value
The JSON.rawJSON() method returns a RawJSON object containing the provided string.
When the RawJSON object is serialized to JSON, the string inside it is output as-is without escaping or additional processing.
Examples
1. Creating a RawJSON Object
This example demonstrates how to create a RawJSON object using JSON.rawJSON().
const raw = JSON.rawJSON('{"name":"Arjun"}');
console.log(raw);
Output
RawJSON { value: '{"name":"Arjun"}' }
- The
RawJSONobject wraps the string as raw JSON content.
2. Serializing a RawJSON Object
When serializing an object containing a RawJSON object, the raw JSON string is included as-is without escaping.
const raw = JSON.rawJSON('{"key":"value"}');
const obj = { data: raw };
const result = JSON.stringify(obj);
console.log(result);
Output
{"data":{"key":"value"}}
- The string
{"key":"value"}is serialized as-is inside thedataproperty.
3. Comparing with Regular Strings
This example highlights the difference between serializing a RawJSON object and a regular string.
const raw = JSON.rawJSON('{"name":"Arjun"}');
const regular = '{"name":"Arjun"}';
const obj1 = { data: raw };
const obj2 = { data: regular };
console.log(JSON.stringify(obj1));
console.log(JSON.stringify(obj2));
Output
{"data":{"name":"Arjun"}}
{"data":"{\"name\":\"Arjun\"}"}
- The
RawJSONstring is included as raw JSON. - The regular string is escaped during serialization.
4. Using JSON.rawJSON() in a Nested Object
Nested RawJSON objects are serialized as-is inside larger objects or arrays.
const nested = {
info: JSON.rawJSON('{"id": 1, "name": "Arjun"}'),
status: "ok"
};
console.log(JSON.stringify(nested));
Output
{"info":{"id":1,"name":"Arjun"},"status":"ok"}
The RawJSON content remains unescaped in the serialized result.
