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

ParameterOptional/RequiredDescription
stringrequiredThe 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,

  1. We define a JSON string jsonString with a key-value pair.
  2. We use the JSON.rawJSON() method to create a raw JSON object from jsonString.
  3. The raw JSON object is stored in the variable raw.
  4. We log raw to the console using console.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,

  1. We define a JSON string jsonString with a key-value pair.
  2. We create a raw JSON object from jsonString using the JSON.rawJSON() method.
  3. We serialize the raw JSON object using the JSON.stringify() method.
  4. The serialized JSON string is stored in the variable serialized.
  5. We log serialized to the console using console.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,

  1. We define an invalid JSON string invalidJsonString.
  2. We attempt to create a raw JSON object using the JSON.rawJSON() method.
  3. An error is thrown because the JSON string is invalid.
  4. 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.