Convert Js Object to Json String

Convert JS object to JSON string

All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

var j = {

"name": "binchen"

};

console.log(JSON.stringify(j));

Safely turning a JSON string into an object

JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.

How to convert JS Object to JSON

Quite literally, JSON is a stricter format for what is basically the right-hand side of a Javascript variable assignment. It's a text-based encoding of Javascript data:

var foo = ...json goes here ...;

JSON can be ANY valid Javascript data-only structure. A boolean, an int, a string, even arrays and objects. What JSON ISN'T is a general serialization format. Something like this

var foo = new Date();
json = JSON.stringify(foo); // json gets the string "2016-08-26 etc..."
newfoo = JSON.parse(json); // newfoo is now a string, NOT a "Date" object.

will not work. The Date object will get serialized to a JSON string, but deserializing the string does NOT give you a Date object again. It'll just be a string.

JSON can only represent DATA, not CODE. That includes expressions

var foo = 2; // "2" is valid json
var foo = 1+1; // invalid - json does not have expressions.
var foo = {"bar":["baz"]}; // also valid JSON
var foo = [1,2,3+4]; // fails - 3+4 is an expression

turn typescript object into json string

Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.

Convert object string to JSON

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

Note that when you eval an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.

I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).

Is there a quick way to convert a JavaScript object to valid JSON in the text editor?

  1. Launch Firefox/Chrome/Safari
  2. Open Firebug/developer tools
  3. Copy/paste your code into the console.
  4. Then type console.log(JSON.stringify(object)) and voila!

    {"item1":"value1","item2":1000,"item3":["a","b","c"],
    "item4":[1,2,3],"item5":{"foo":"bar"}}
  5. Copy/paste back into your text editor.

For more control over the formatting, I have a free online webpage:

http://phrogz.net/JS/NeatJSON

that lets you paste JSON or JS values in one box and see JSON at the bottom, with lots of knobs and sliders to adjust how it looks. For example, the JS value ["foo","bar",{dogs:42,piggies:0,cats:7},{jimmy:[1,2,3,4,5],jammy:3.14159265358979,hot:"pajammy"}] can be formatted like any of the following (and more):

[
"foo", <- adjustable indentation
"bar",
{"dogs":42,"piggies":0,"cats":7}, <- small objects on one line!
{
"jimmy":[1,2,3,4,5], <- small arrays on one line!
"jammy":3.142, <- decimal precision!
"hot":"pajammy"
}
]
[
"foo",
"bar",
{ "cats":7, "dogs":42, "piggies":0 }, <- spaces inside braces!
{
"hot":"pajammy", <- sort object keys!
"jammy":3.14159265358979,
"jimmy":[ 1, 2, 3, 4, 5 ] <- spaces after commas!
}
]
[ "foo",                           <- 'short' format puts first value
"bar", <- on same line as opening bracket...
{ "dogs" : 42,
"piggies" : 0,
"cats" : 7 }, <- ...and close bracket with last value!
{ "jimmy" : [ 1, 2, 3, 4, 5 ],
"jammy" : 3.14159265358979, <- spaces around colons!
"hot" : "pajammy" } ] <- align object values!

Screenshot of NeatJSON webpage

How to convert FormData (HTML5 object) to JSON

You could also use forEach on the FormData object directly:

var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);


UPDATE:

And for those who prefer the same solution with ES6 arrow functions:

var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);

UPDATE 2:

And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):

var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);

Here a Fiddle demonstrating the use of this method with a simple multi select list.

UPDATE 3:

As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData object directly without converting it. As simple as this:

var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);

See also Using FormData Objects on MDN for reference:

UPDATE 4:

As mentioned in one of the comments below my answer the JSON stringify method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify.

In the description is also mentioned that:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

This means that you can supply your own toJSON serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.



Related Topics



Leave a reply



Submit