JSON.stringify output to div in pretty print way
Asked Answered
L

14

282

I JSON.stringify a json object by

result = JSON.stringify(message, my_json, 2)

The 2 in the argument above is supposed to pretty print the result. It does this if I do something like alert(result). However, I want to output this to the user by appending it inside a div. When I do this I get just a single line showing up. (I don't think it is working because the breaks and spaces are not being interpreted as html?)

{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }

Is there a way to output the result of JSON.stringify to a div in a pretty print way?

Lesley answered 31/5, 2013 at 17:22 Comment(3)
Use a pre element? Use a prettify library?Thromboplastic
Using PHP, this was helpful for me: https://mcmap.net/q/110103/-php-quot-pretty-print-quot-json_encode-duplicateOswaldooswalt
Does this answer your question? Render a string in HTML and preserve spaces and linebreaksSpasm
T
709

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

var data = {
  "data": {
    "x": "1",
    "y": "1",
    "url": "http://url.com"
  },
  "event": "start",
  "show": 1,
  "id": 50
}


document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>
Truckle answered 31/5, 2013 at 17:30 Comment(9)
pre tells the browser engine that the content inside is pre-formatted and it can be displayed without any modification. So browser will not remove white spaces, new lines etc. code is for making it more semantic and denotes that the content inside is a code snippet. It has nothing to with formatting. It is advised to use like this, <pre><code> /* Your code snippet here. */ </code></pre>Truckle
in order to avoid long lines to go out of the container the pre tag is a child of, one should add the following css rules to the pre tag: https://mcmap.net/q/53273/-how-do-i-wrap-text-in-a-pre-tagHeddy
I always forget about the <pre> tag.Firsthand
but if I use "array": [1,2,3,4] in above js fiddle in data . it splits array in multiple lines. why?Alesha
@iGod: That is how stringify formats. You can override it by using a 'replacer' function which is the second parameter as shown below. JSON.stringify({name: "Diode", details: {age: 123, place: "xyz"}, list: [1, 2, 3, 4, 5]},function(k,v){ if(v instanceof Array) return JSON.stringify(v); return v; },2);Truckle
@Truckle I would also mention it is better to use .textContent instead of .innerHTML because it will escape dangerous html that might be in the json: developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/…Lowelllowenstein
Unfortunately you get an Error: 'element' is possibly 'null' when handling it this way.Plane
Hi @Truckle I saw you mentioned <code> should be used , but in your code example, you only put <pre> this confused me. Will the <code> section generated automatically? If not, am I supposed to just put the <code> inside <pre> and assign the id "json" to the <code> tag?Wandering
I tried to put nicely formatted JSON into an email using HTML in my Java Spring Boot project. Using only <pre> didn't work for me. <pre><code> /* Your code snippet here. */ </code></pre> worked.Wildlife
O
44

Make sure the JSON output is in a <pre> tag.

Openmouthed answered 31/5, 2013 at 17:26 Comment(0)
C
30

If your <pre> tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:

HTML:

<pre id="json">{"some":"JSON string"}</pre>

JavaScript:

    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);
    })();

or jQuery:

    $(formatJson);

    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
    }
Crocidolite answered 10/5, 2019 at 6:32 Comment(1)
Good work, @thinkOfaNumber. I used a one-line rewrite of your JS above: JSON.stringify(JSON.parse(myJSON), undefined, 2).Aculeus
G
11

My proposal is based on:

  • replace each '\n' (newline) with a <br>
  • replace each space with &nbsp;

var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };


document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
     .replace(/\n( *)/g, function (match, p1) {
         return '<br>' + '&nbsp;'.repeat(p1.length);
     });
<div id="newquote"></div>
Glooming answered 1/2, 2019 at 21:21 Comment(0)
T
9

Full disclosure I am the author of this package but another way to output JSON or JavaScript objects in a readable way complete with being able skip parts, collapse them, etc. is nodedump, https://github.com/ragamufin/nodedump

Technetium answered 8/1, 2015 at 3:26 Comment(0)
S
7

Wrap it by pre tag

<pre> { JSON.stringify(todos, null, 4)}</pre>

and the output will be

[
    {
        "id": "6cbc8fc4-a89e-4afa-abc1-f72f27b14271",
        "title": "shakil",
        "completed": false
    },
    {
        "id": "5ee68df8-e152-46ae-82e2-8eb49f477d6f",
        "title": "kobir",
        "completed": false
    }
]
Stash answered 12/7, 2022 at 9:43 Comment(2)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewMarchese
I tried that and everything was in one line with scroll on X-axisMeurer
S
6

Consider your REST API returns:

{"Intent":{"Command":"search","SubIntent":null}}

Then you can do the following to print it in a nice format:

<pre id="ciResponseText">Output will de displayed here.</pre>   

var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);   
Spinach answered 11/4, 2017 at 9:16 Comment(0)
R
6

A lot of people create very strange responses to these questions that make alot more work than necessary.

The easiest way to do this consists of the following

  1. Parse JSON String using JSON.parse(value)
  2. Stringify Parsed string into a nice format - JSON.stringify(input,undefined,2)
  3. Set output to the value of step 2.

In actual code, an example will be (combining all steps together):

    var input = document.getElementById("input").value;
    document.getElementById("output").value = JSON.stringify(JSON.parse(input),undefined,2);

output.value is going to be the area where you will want to display a beautified JSON.

Readytowear answered 12/8, 2020 at 12:39 Comment(0)
G
3

print the state of a component with JSX

render() {
  return (
    <div>
      <h1>Adopt Me!</h1>
      <pre>
        <code>{JSON.stringify(this.state, null, 4)}</code>
      </pre>
    </div>
  );
}

stringify

Guria answered 21/4, 2019 at 20:13 Comment(0)
C
1

use style white-space: pre the <pre> tag also modifies the text format which may be undesirable.

Claro answered 12/5, 2017 at 19:9 Comment(0)
C
1

it's for Laravel, Codeigniter Html: <pre class="jsonPre"> </pre>

Controller: Return the JSON value from the controller as like as

return json_encode($data, JSON_PRETTY_PRINT);

In script: <script> $('.jsonPre').html(result); </script>

result will be

result will be

Capacitor answered 21/9, 2021 at 13:7 Comment(1)
he asked for JS, not laravel.Drunk
H
0

for those who want to show collapsible json can use renderjson

Here is the example by embedding the render js javascript in html

<!DOCTYPE html>
<html>

<head>

<script type="application/javascript">
// Copyright © 2013-2014 David Caldwell <[email protected]>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

// Usage
// -----
// The module exports one entry point, the `renderjson()` function. It takes in
// the JSON you want to render as a single argument and returns an HTML
// element.
//
// Options
// -------
// renderjson.set_icons("+", "-")
//   This Allows you to override the disclosure icons.
//
// renderjson.set_show_to_level(level)
//   Pass the number of levels to expand when rendering. The default is 0, which
//   starts with everything collapsed. As a special case, if level is the string
//   "all" then it will start with everything expanded.
//
// renderjson.set_max_string_length(length)
//   Strings will be truncated and made expandable if they are longer than
//   `length`. As a special case, if `length` is the string "none" then
//   there will be no truncation. The default is "none".
//
// renderjson.set_sort_objects(sort_bool)
//   Sort objects by key (default: false)
//
// Theming
// -------
// The HTML output uses a number of classes so that you can theme it the way
// you'd like:
//     .disclosure    ("⊕", "⊖")
//     .syntax        (",", ":", "{", "}", "[", "]")
//     .string        (includes quotes)
//     .number
//     .boolean
//     .key           (object key)
//     .keyword       ("null", "undefined")
//     .object.syntax ("{", "}")
//     .array.syntax  ("[", "]")

var module;
(module || {}).exports = renderjson = (function () {
  var themetext = function (/* [class, text]+ */) {
    var spans = [];
    while (arguments.length)
      spans.push(append(span(Array.prototype.shift.call(arguments)),
        text(Array.prototype.shift.call(arguments))));
    return spans;
  };
  var append = function (/* el, ... */) {
    var el = Array.prototype.shift.call(arguments);
    for (var a = 0; a < arguments.length; a++)
      if (arguments[a].constructor == Array)
        append.apply(this, [el].concat(arguments[a]));
      else
        el.appendChild(arguments[a]);
    return el;
  };
  var prepend = function (el, child) {
    el.insertBefore(child, el.firstChild);
    return el;
  }
  var isempty = function (obj) {
    for (var k in obj) if (obj.hasOwnProperty(k)) return false;
    return true;
  }
  var text = function (txt) { return document.createTextNode(txt) };
  var div = function () { return document.createElement("div") };
  var span = function (classname) {
    var s = document.createElement("span");
    if (classname) s.className = classname;
    return s;
  };
  var A = function A(txt, classname, callback) {
    var a = document.createElement("a");
    if (classname) a.className = classname;
    a.appendChild(text(txt));
    a.href = '#';
    a.onclick = function () { callback(); return false; };
    return a;
  };

  function _renderjson(json, indent, dont_indent, show_level, max_string, sort_objects) {
    var my_indent = dont_indent ? "" : indent;

    var disclosure = function (open, placeholder, close, type, builder) {
      var content;
      var empty = span(type);
      var show = function () {
        if (!content) append(empty.parentNode,
          content = prepend(builder(),
            A(renderjson.hide, "disclosure",
              function () {
                content.style.display = "none";
                empty.style.display = "inline";
              })));
        content.style.display = "inline";
        empty.style.display = "none";
      };
      append(empty,
        A(renderjson.show, "disclosure", show),
        themetext(type + " syntax", open),
        A(placeholder, null, show),
        themetext(type + " syntax", close));

      var el = append(span(), text(my_indent.slice(0, -1)), empty);
      if (show_level > 0)
        show();
      return el;
    };

    if (json === null) return themetext(null, my_indent, "keyword", "null");
    if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");

    if (typeof (json) == "string" && json.length > max_string)
      return disclosure('"', json.substr(0, max_string) + " ...", '"', "string", function () {
        return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));
      });

    if (typeof (json) != "object") // Strings, numbers and bools
      return themetext(null, my_indent, typeof (json), JSON.stringify(json));

    if (json.constructor == Array) {
      if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");

      return disclosure("[", " ... ", "]", "array", function () {
        var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
        for (var i = 0; i < json.length; i++)
          append(as,
            _renderjson(json[i], indent + "    ", false, show_level - 1, max_string, sort_objects),
            i != json.length - 1 ? themetext("syntax", ",") : [],
            text("\n"));
        append(as, themetext(null, indent, "array syntax", "]"));
        return as;
      });
    }

    // object
    if (isempty(json))
      return themetext(null, my_indent, "object syntax", "{}");

    return disclosure("{", "...", "}", "object", function () {
      var os = append(span("object"), themetext("object syntax", "{", null, "\n"));
      for (var k in json) var last = k;
      var keys = Object.keys(json);
      if (sort_objects)
        keys = keys.sort();
      for (var i in keys) {
        var k = keys[i];
        append(os, themetext(null, indent + "    ", "key", '"' + k + '"', "object syntax", ': '),
          _renderjson(json[k], indent + "    ", true, show_level - 1, max_string, sort_objects),
          k != last ? themetext("syntax", ",") : [],
          text("\n"));
      }
      append(os, themetext(null, indent, "object syntax", "}"));
      return os;
    });
  }

  var renderjson = function renderjson(json) {
    var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.max_string_length, renderjson.sort_objects));
    pre.className = "renderjson";
    return pre;
  }
  renderjson.set_icons = function (show, hide) {
    renderjson.show = show;
    renderjson.hide = hide;
    return renderjson;
  };
  renderjson.set_show_to_level = function (level) {
    renderjson.show_to_level = typeof level == "string" &&
      level.toLowerCase() === "all" ? Number.MAX_VALUE
      : level;
    return renderjson;
  };
  renderjson.set_max_string_length = function (length) {
    renderjson.max_string_length = typeof length == "string" &&
      length.toLowerCase() === "none" ? Number.MAX_VALUE
      : length;
    return renderjson;
  };
  renderjson.set_sort_objects = function (sort_bool) {
    renderjson.sort_objects = sort_bool;
    return renderjson;
  };
  // Backwards compatiblity. Use set_show_to_level() for new code.
  renderjson.set_show_by_default = function (show) {
    renderjson.show_to_level = show ? Number.MAX_VALUE : 0;
    return renderjson;
  };
  renderjson.set_icons('⊕', '⊖');
  renderjson.set_show_by_default(false);
  renderjson.set_sort_objects(false);
  renderjson.set_max_string_length("none");
  return renderjson;
})();
</script>

</head>


<body>
  <div id="dest"></div>
</body>
<script type="application/javascript">
  document.getElementById("dest").appendChild(
    renderjson.set_show_by_default(true)
      //.set_show_to_level(2)
      //.set_sort_objects(true)
      //.set_icons('+', '-')
      .set_max_string_length(100)
      ([
        {
          "glossary": {
            "title": "example glossary",
            "GlossDiv": {
              "title": "S",
              "GlossList": {
                "GlossEntry": {
                  "ID": "SGML",
                  "SortAs": "SGML",
                  "GlossTerm": "Standard Generalized Markup Language",
                  "Acronym": "SGML",
                  "Abbrev": "ISO 8879:1986",
                  "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                  },
                  "GlossSee": "markup"
                }
              }
            }
          }
        },
        {
          "menu": {
            "id": "file",
            "value": "File",
            "popup": {
              "menuitem": [
                { "value": "New", "onclick": "CreateNewDoc()" },
                { "value": "Open", "onclick": "OpenDoc()" },
                { "value": "Close", "onclick": "CloseDoc()" }
              ]
            }
          }
        },

        {
          "widget": {
            "debug": "on",
            "window": {
              "title": "Sample Konfabulator Widget",
              "name": "main_window",
              "width": 500,
              "height": 500
            },
            "image": {
              "src": "Images/Sun.png",
              "name": "sun1",
              "hOffset": 250,
              "vOffset": 250,
              "alignment": "center"
            },
            "text": {
              "data": "Click Here",
              "size": 36,
              "style": "bold",
              "name": "text1",
              "hOffset": 250,
              "vOffset": 100,
              "alignment": "center",
              "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
            }
          }
        },

        {
          "web-app": {
            "servlet": [
              {
                "servlet-name": "cofaxCDS",
                "servlet-class": "org.cofax.cds.CDSServlet",
                "init-param": {
                  "configGlossary:installationAt": "Philadelphia, PA",
                  "configGlossary:adminEmail": "[email protected]",
                  "configGlossary:poweredBy": "Cofax",
                  "configGlossary:poweredByIcon": "/images/cofax.gif",
                  "configGlossary:staticPath": "/content/static",
                  "templateProcessorClass": "org.cofax.WysiwygTemplate",
                  "templateLoaderClass": "org.cofax.FilesTemplateLoader",
                  "templatePath": "templates",
                  "templateOverridePath": "",
                  "defaultListTemplate": "listTemplate.htm",
                  "defaultFileTemplate": "articleTemplate.htm",
                  "useJSP": false,
                  "jspListTemplate": "listTemplate.jsp",
                  "jspFileTemplate": "articleTemplate.jsp",
                  "cachePackageTagsTrack": 200,
                  "cachePackageTagsStore": 200,
                  "cachePackageTagsRefresh": 60,
                  "cacheTemplatesTrack": 100,
                  "cacheTemplatesStore": 50,
                  "cacheTemplatesRefresh": 15,
                  "cachePagesTrack": 200,
                  "cachePagesStore": 100,
                  "cachePagesRefresh": 10,
                  "cachePagesDirtyRead": 10,
                  "searchEngineListTemplate": "forSearchEnginesList.htm",
                  "searchEngineFileTemplate": "forSearchEngines.htm",
                  "searchEngineRobotsDb": "WEB-INF/robots.db",
                  "useDataStore": true,
                  "dataStoreClass": "org.cofax.SqlDataStore",
                  "redirectionClass": "org.cofax.SqlRedirection",
                  "dataStoreName": "cofax",
                  "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
                  "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
                  "dataStoreUser": "sa",
                  "dataStorePassword": "dataStoreTestQuery",
                  "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
                  "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
                  "dataStoreInitConns": 10,
                  "dataStoreMaxConns": 100,
                  "dataStoreConnUsageLimit": 100,
                  "dataStoreLogLevel": "debug",
                  "maxUrlLength": 500
                }
              },
              {
                "servlet-name": "cofaxEmail",
                "servlet-class": "org.cofax.cds.EmailServlet",
                "init-param": {
                  "mailHost": "mail1",
                  "mailHostOverride": "mail2"
                }
              },
              {
                "servlet-name": "cofaxAdmin",
                "servlet-class": "org.cofax.cds.AdminServlet"
              },

              {
                "servlet-name": "fileServlet",
                "servlet-class": "org.cofax.cds.FileServlet"
              },
              {
                "servlet-name": "cofaxTools",
                "servlet-class": "org.cofax.cms.CofaxToolsServlet",
                "init-param": {
                  "templatePath": "toolstemplates/",
                  "log": 1,
                  "logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
                  "logMaxSize": "",
                  "dataLog": 1,
                  "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
                  "dataLogMaxSize": "",
                  "removePageCache": "/content/admin/remove?cache=pages&id=",
                  "removeTemplateCache": "/content/admin/remove?cache=templates&id=",
                  "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
                  "lookInContext": 1,
                  "adminGroupID": 4,
                  "betaServer": true
                }
              }],
            "servlet-mapping": {
              "cofaxCDS": "/",
              "cofaxEmail": "/cofaxutil/aemail/*",
              "cofaxAdmin": "/admin/*",
              "fileServlet": "/static/*",
              "cofaxTools": "/tools/*"
            },

            "taglib": {
              "taglib-uri": "cofax.tld",
              "taglib-location": "/WEB-INF/tlds/cofax.tld"
            }
          }
        },

        {
          "menu": {
            "header": "SVG Viewer",
            "items": [
              { "id": "Open" },
              { "id": "OpenNew", "label": "Open New" },
              null,
              { "id": "ZoomIn", "label": "Zoom In" },
              { "id": "ZoomOut", "label": "Zoom Out" },
              { "id": "OriginalView", "label": "Original View" },
              null,
              { "id": "Quality" },
              { "id": "Pause" },
              { "id": "Mute" },
              null,
              { "id": "Find", "label": "Find..." },
              { "id": "FindAgain", "label": "Find Again" },
              { "id": "Copy" },
              { "id": "CopyAgain", "label": "Copy Again" },
              { "id": "CopySVG", "label": "Copy SVG" },
              { "id": "ViewSVG", "label": "View SVG" },
              { "id": "ViewSource", "label": "View Source" },
              { "id": "SaveAs", "label": "Save As" },
              null,
              { "id": "Help" },
              { "id": "About", "label": "About Adobe CVG Viewer..." }
            ]
          }
        },
        {
          "empty": {
            "object": {},
            "array": []
          }
        },
        {
          "really_long": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla posuere, orci quis laoreet luctus, nunc neque condimentum arcu, sed tristique sem erat non libero. Morbi et velit non justo rutrum pulvinar. Nam pellentesque laoreet lacus eget sollicitudin. Quisque maximus mattis nisl, eget tempor nisi pulvinar et. Nullam accumsan sapien sapien, non gravida turpis consectetur non. Etiam in vestibulum neque. Donec porta dui sit amet turpis efficitur laoreet. Duis eu convallis ex, vel volutpat lacus. Donec sit amet nunc a orci fermentum luctus."
        }
      ]));
</script>

</html>
Hydrant answered 22/1, 2020 at 13:14 Comment(0)
G
0

You can also use react-json-tree package if you are using React.

I created a component for it like below that accept a data props.

import React from 'react';
import JSONTree from 'react-json-tree'
import './style.css';

const theme = {
    scheme: 'monokai',
    base00: '#272822',
    base01: '#383830',
    base02: '#49483e',
    base03: '#75715e',
    base04: '#a59f85',
    base05: '#f8f8f2',
    base06: '#f5f4f1',
    base07: '#f9f8f5',
    base08: '#f92672',
    base09: '#fd971f',
    base0A: '#f4bf75',
    base0B: '#a6e22e',
    base0C: '#a1efe4',
    base0D: '#66d9ef',
    base0E: '#ae81ff',
    base0F: '#cc6633',
};

const TreeView = (props) => {

    return (
        <div className="tree-container">
            <JSONTree
                data={props.data}
                theme={theme}
                invertTheme={true}
                hideRoot
                labelRenderer={([key]) => {
                    return <strong>{key}:</strong>
                }}
                valueRenderer={(valueAsString, value) => {
                    return <span className="capitalize">{value}</span>;
                }}
                getItemString={() => ''}
            />
        </div>
    );
}

export default TreeView;

Then I use it inside an html element like below after importing the component.

<div>
 <TreeView data={s.value} />
</div>
Gardner answered 9/11, 2021 at 3:43 Comment(0)
S
0

You can use a npm package - [jsontohtml-render][1]. It also provides file if you want to use it inside html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <!-- Add a script file -->
    <script src="https://cdn.jsdelivr.net/gh/ArjunVarshney/jsontohtml-render@latest/dist/index.js"></script>
    <!-- Add a script file as above -->
  </head>

  <body>
    <div id="json"></div>
    <script>
      // Use it to update html as follows
      document.getElementById('json').innerHTML = jsontohtml({ hello: 'moto' });
    </script>
  </body>
</html>

It also works with react/next:

import { jsontohtml } from 'jsontohtml-render';

export default function Home() {
  // use it as show below
  const html = jsontohtml({
    hello: ['this', 'is', 'some', 'text'],
    arrayofobjects: [{ something: [1, 2, 3] }, {}],
  });

  return <div className="h-full w-full" dangerouslySetInnerHTML={{ __html: html }}></div>;
}

I made this package for the purpose of pretty printing json response on the docs page of an api (inside a div) [1]: https://www.npmjs.com/package/jsontohtml-render

Schmooze answered 9/9, 2023 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.