How to use Lodash _.prototype.toJSON() Method In Javascript

The _.prototype.toJSON() method of Sequence in lodash is used to execute the chain sequence in order to solve the unwrapped value.

NOTE: To implement this method for converting the JS object in the JSON string you need to install the lodash module into your local system.

Syntax:

const _ = require('lodash');
const myObj = {};
const jsonString = _(myObj).toJSON();

Example: The belowe example illustrate how to use the _.prototype.toJSON() method to convert the JavaScript obeject into an array.

Javascript




// Sample JS object
const _ = require('lodash');
const geeks = {
    name: "Shubham",
    age: 21,
    Intern: "Geeksoforgeeks",
    Place: "Work from Home"
};
let res = _(geeks).toJSON();
console.log(res);


Output:

{"name":"Shubham","age":21,"Intern":"Geeksoforgeeks","Place":"Work from Home"}

How to Convert JS Object to JSON String in JQuery/Javascript?

Whenever we send the data to a web server, we send the data in the form of a string.

To Convert JS Object to JSON String in JQuery/Javascript we can use the following approaches:

Table of Content

  • Using JSON.stringify() Method
  • Using Lodash _.prototype.toJSON() Method
  • Using jQuery

Similar Reads

Method 1: Using JSON.stringify() Method

The JSON.stringify() method in JavaScript allows us to take a JavaScript object or Array and create a JSON string out of it.  Store the JSON object in the variable. Pass that variable in the JSON.stringify() as an argument. It will return the value which is to be converted into a JSON string....

Method 2: Using Lodash _.prototype.toJSON() Method

...

Method 3: Using jQuery

The _.prototype.toJSON() method of Sequence in lodash is used to execute the chain sequence in order to solve the unwrapped value....