Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object to formatted string

How to output an object as a readable string with formatting (structured like with <pre>) ?

No jQuery possible.

My object looks like this using console.log.

Object
   title: "Another sting"
   type: "tree"
   options: Object
      paging: "20"
      structuretype: "1"
   columns: Object
      ...
   description: "This is a string"
   ...

What is the best to convert it to a structured string?

My attempt:

I tried using stringify() to get the JSON structure. I could then write my own parser, but maybe there are already any implementations?

like image 640
Shlomo Avatar asked Oct 18 '12 08:10

Shlomo


People also ask

How do you turn an object into a string in JavaScript?

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

Which static method is used to convert JavaScript object to string?

stringify() method. “Stringification” is the process of converting a JavaScript object to a string. This operation is performed when you want to serialize data to string for sending it to some web server or storing it in a database.

Which method is used to convert JS object to JSON format?

With the help of the JSON. stringify() method, you can easily convert a JavaScript object into a string that will have a valid JSON format. It is typically used for generating a ready-made string that can be delivered to a server. This write-up will explain JSON.

What is Stringify in JavaScript?

The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


1 Answers

JSON.stringify includes a formatting argument:

JSON.stringify(value[, replacer [, space]])

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will indented by this string (or the first ten characters of it).

Using a tab character mimics standard pretty-print appearance

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

Is that enough formatting for what you need? E.g. try:

 JSON.stringify( object, null, 2 );

Otherwise, http://code.google.com/p/google-code-prettify/ is a standalone JSON to HTML pretty printer. Used by stackoverflow and google code, I believe.

like image 147
sync Avatar answered Sep 28 '22 11:09

sync