JavaScript JSON rawJSON()
Syntax & Examples
rawJSON() static-method
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.
Syntax of rawJSON()
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.
Parameters
| Parameter | Optional/Required | Description |
|---|---|---|
string | required | The string containing the JSON text. This text must be valid JSON. |
Return Type
JSON.rawJSON() returns value of type Object.
✐ Examples
1 Creating a raw JSON object
In JavaScript, we can use the JSON.rawJSON() method to create a raw JSON object from a valid JSON string.
For example,
- We define a JSON string
jsonStringwith a key-value pair. - We use the
JSON.rawJSON()method to create a raw JSON object fromjsonString. - The raw JSON object is stored in the variable
raw. - We log
rawto the console usingconsole.log()method.
JavaScript Program
const jsonString = '{"key": "value"}';
const raw = JSON.rawJSON(jsonString);
console.log(raw);Output
{ key: 'value' }2 Serializing a raw JSON object
In JavaScript, we can use the JSON.stringify() method to serialize a raw JSON object created by JSON.rawJSON().
For example,
- We define a JSON string
jsonStringwith a key-value pair. - We create a raw JSON object from
jsonStringusing theJSON.rawJSON()method. - We serialize the raw JSON object using the
JSON.stringify()method. - The serialized JSON string is stored in the variable
serialized. - We log
serializedto the console usingconsole.log()method.
JavaScript Program
const jsonString = '{"key": "value"}';
const raw = JSON.rawJSON(jsonString);
const serialized = JSON.stringify(raw);
console.log(serialized);Output
{"key":"value"}3 Handling invalid JSON text
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,
- We define an invalid JSON string
invalidJsonString. - We attempt to create a raw JSON object using the
JSON.rawJSON()method. - An error is thrown because the JSON string is invalid.
- We catch and log the error to the console using
console.error()method.
JavaScript Program
const invalidJsonString = '{key: "value"}';
try {
const raw = JSON.rawJSON(invalidJsonString);
} catch (error) {
console.error('Invalid JSON:', error);
}Output
Invalid JSON: SyntaxError: Unexpected token k in JSON at position 1
Summary
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.