Asked 7 years ago
6 Jan 2017
Views 1202
Rasi

Rasi posted

Serializing to JSON in JavaScript

trying to convert array or object to JSON format ,

var filterArray=[".info",".com"];
var domainSearchObject={ ".info",".com",".org"}

i need array to JSON and object to JSON so i can pass it in ajax request


$.ajax({
    type: "POST",
    url: "/search",
    data: "{'domainsearch':['info','com','.org']}",
Nilesh

Nilesh
answered Apr 24 '23 00:00

JavaScript has a built-in method called JSON.stringify() that can be used to serialize data into JSON format. This method takes a JavaScript object or value as its argument and returns a string representation of that object in JSON format.

Here's an example of using JSON.stringify() in JavaScript:



const data = {
  name: "John",
  age: 30,
  city: "New York"
};

const jsonString = JSON.stringify(data);

console.log(jsonString);

In this example, we have a JavaScript object called data with three properties: name , age , and city . We then call JSON.stringify() with the data object as the argument, which returns a JSON string. The resulting string is stored in the jsonString variable and then logged to the console.

It's important to note that JSON.stringify( ) automatically removes any functions or properties of an object that cannot be serialized to JSON, such as undefined or function types. If you need to preserve these values, you can pass a second argument to JSON.stringify(), which is a "replacer" function that allows you to specify which values to include or exclude in the JSON serialization process.



const data = {
  name: "John",
  age: 30,
  city: "New York",
  greeting: function() {
    return "Hello, " + this.name + "!";
  }
};

const jsonString = JSON.stringify(data, function(key, value) {
  if (typeof value === "function") {
    return value.toString();
  }
  return value;
});


console.log(jsonString);
In this example, we have added a greeting property to the data object that is a function. To include this function in the JSON serialization, we pass a replacer function as the second argument to JSON.stringif y(). This function checks if a value is a function, and if so, returns a string representation of the function using the toString() method. If the value is not a function, it is returned as is.

By default, JSON.stringify() adds double quotes around property names in the resulting JSON string. If you prefer single quotes or no quotes, you can pass a third argument to JSON.stringify() that specifies the indentation and quote style.



const data = {
  name: "John",
  age: 30,
  city: "New York"
};

const jsonString = JSON.stringify(data, null, 2);

console.log(jsonString);

In this example, we pass a third argument to JSON.stringify() that specifies an indentation of two spaces for each level of nesting. This makes the resulting JSON string more readable.
Post Answer