The JSON.rawJSON() method creates a 'raw JSON' object containing a piece of JSON text. This method ensures that when the object is serialized, it is treated as if it is already a piece of JSON. The input text must be valid JSON.
The syntax of JSON.rawJSON() static-method is:
JSON.rawJSON(string)
This rawJSON() static-method of JSON creates a "raw JSON" object containing a piece of JSON text. When serialized to JSON, the raw JSON object is treated as if it is already a piece of JSON. This text is required to be valid JSON.
Parameter | Optional/Required | Description |
---|---|---|
string | required | The string containing the JSON text. This text must be valid JSON. |
JSON.rawJSON() returns value of type Object
.
In JavaScript, we can use the JSON.rawJSON()
method to create a raw JSON object from a valid JSON string.
For example,
jsonString
with a key-value pair.JSON.rawJSON()
method to create a raw JSON object from jsonString
.raw
.raw
to the console using console.log()
method.const jsonString = '{"key": "value"}';
const raw = JSON.rawJSON(jsonString);
console.log(raw);
{ key: 'value' }
In JavaScript, we can use the JSON.stringify()
method to serialize a raw JSON object created by JSON.rawJSON()
.
For example,
jsonString
with a key-value pair.jsonString
using the JSON.rawJSON()
method.JSON.stringify()
method.serialized
.serialized
to the console using console.log()
method.const jsonString = '{"key": "value"}';
const raw = JSON.rawJSON(jsonString);
const serialized = JSON.stringify(raw);
console.log(serialized);
{"key":"value"}
In JavaScript, the JSON.rawJSON()
method requires the input text to be valid JSON. If the input text is invalid, an error will be thrown.
For example,
invalidJsonString
.JSON.rawJSON()
method.console.error()
method.const invalidJsonString = '{key: "value"}';
try {
const raw = JSON.rawJSON(invalidJsonString);
} catch (error) {
console.error('Invalid JSON:', error);
}
Invalid JSON: SyntaxError: Unexpected token k in JSON at position 1
In this JavaScript tutorial, we learned about rawJSON() static-method of JSON: the syntax and few working examples with output and detailed explanation for each example.