Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert json to a string using jquery

I have a nested json. I want to post it as a form input value.

But, seems like jquery puts "Object object" string into the value.

It seems easier to pass around the string and convert into the native form I need, than dealing with json as I don't need to change anything once it is generated.

What is the simplest way to convert a json

var json = {
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
     "streetAddress": "21 2nd Street",
     "city": "New York",
     "state": "NY",
     "postalCode": "10021"
     },
     "phoneNumber": [
     { "type": "home", "number": "212 555-1234" },
     { "type": "fax", "number": "646 555-4567" }
     ],
     "newSubscription": false,
     "companyName": null
 };

into its string form?

var json = '{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address": {
     "streetAddress": "21 2nd Street",
     "city": "New York",
     "state": "NY",
     "postalCode": "10021"
     },
     "phoneNumber": [
     { "type": "home", "number": "212 555-1234" },
     { "type": "fax", "number": "646 555-4567" }
     ],
     "newSubscription": false,
     "companyName": null
 }'

Following doesn't do what I need:

Json.stringify()
like image 947
lprsd Avatar asked Mar 16 '10 10:03

lprsd


People also ask

How can I convert JSON to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How can you parse JSON via jQuery?

JQuery | parseJSON() method This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value. Parameters: The parseXML() method accepts only one parameter that is mentioned above and described below: json: This parameter is the well-formed JSON string to be parsed.

How does jQuery handle JSON data?

To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery. getJSON( ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.

What is JSON Stringify and JSON parse?

parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string. Follow this answer to receive notifications.


1 Answers

jQuery doesn't have a method for JSON stringifying native objects. You will need json2.js which will provide the JSON.stringify() method to browsers that don't already support it.

like image 51
Andy E Avatar answered Sep 19 '22 03:09

Andy E