No need to use difficult regex, we can use functionality from JSON.stringify(object, undefined, 2) to get beautifully rendered strings from JSON.

var obj={"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"}}}}}


var pretty = JSON.stringify(obj, undefined, 2);

var ugly = document.getElementById('myTextArea').value; document.getElementById('myTextArea').value = pretty;
Answer from inovramadani on Stack Overflow
🌐
CodePen
codepen.io › okproject › pen › meemGQ
Pretty Json Inside TextArea
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing. If active, Pens will autosave every 30 seconds after being saved once. If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update. If enabled, your code will be formatted ...
Discussions

React: how to build editable JSON text
Are you making mutations to the JSON string returned by the server? If so, this is not the approach you want to go with and it would be very difficult to manage. Parse the JSON to an object and make mutations on the object directly. Build a form based on the shape of the object that captures the mutations and on submit, send that data back to the server. More on reddit.com
🌐 r/learnprogramming
4
1
December 5, 2021
html - How to format output text to show as code in react - Stack Overflow
It's pretty hard in a semantic container to format text to looks like json but you can use a react package like react-json-pretty or you can make a JSON.stringify(json,undefined,2) and pass it in a semantic TextArea that you add into your container and "play" with css to make looks better. More on stackoverflow.com
🌐 stackoverflow.com
JSON Viewer with Editor
Very cool. I could see using this in my admin dashboard for live updating my JSON-based application configuration. One tiny visual gripe: The default height of the text-area is too tall for single line inputs. The text-area should be the same size as the input, and grow as needed. This would also eliminate any jank seen when toggling edit mode. More on reddit.com
🌐 r/reactjs
9
26
June 25, 2017
Way to edit JSON strings for non engineer
Seems trivial to hook up a backend that has the git credentials that can list the json available to a react admin portal to navigate through the lexicon tree and present a up to edit/add words or phrases per language. The backend would then commit the submitted changes either as an update or as a PR More on reddit.com
🌐 r/reactjs
9
6
April 27, 2024
Top answer
1 of 6
201

The syntax highlighting is tough but check out this fiddle for pretty printing a json object entered in a text area. Do note that the JSON has to be valid for this to work. (Use the dev console to catch errors.) Check jsLint for valid json.

The HTML:

<textarea id="myTextArea" cols=50 rows=10></textarea>
<button onclick="prettyPrint()">Pretty Print</button>

The js:

function prettyPrint() {
    var ugly = document.getElementById('myTextArea').value;
    var obj = JSON.parse(ugly);
    var pretty = JSON.stringify(obj, undefined, 4);
    document.getElementById('myTextArea').value = pretty;
}

First try simple input like: {"a":"hello","b":123}

Simple pretty printing of JSON can be done rather easily. Try this js code: (jsFiddle here)

// arbitrary js object:
var myJsObj = {a:'foo', 'b':'bar', c:[false,2,null, 'null']};

// using JSON.stringify pretty print capability:
var str = JSON.stringify(myJsObj, undefined, 4);

// display pretty printed object in text area:
document.getElementById('myTextArea').innerHTML = str;

For this HTML:

<textarea id="myTextArea" cols=50 rows=25></textarea>

And check out JSON.stringify documentation.

2 of 6
11

Late answer but modern one, use the secret intendation parameter.

I usually go for:

JSON.stringify(myData, null, 4);


Here's the code definition, it explains it well.

stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;

/**
 * Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
 * @param value A JavaScript value, usually an object or array, to be converted.
 * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified.
 * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
 */
🌐
CodeSandbox
codesandbox.io › s › text-area-json-format-yjy2f8
text-area-json-format - CodeSandbox
November 17, 2023 - CodeSandbox is a cloud development platform that empowers developers to code, collaborate and ship projects of any size from any device in record time.
Published   Nov 16, 2023
Author   waen.saranya
🌐
GitHub
gist.github.com › kristopherjohnson › 70d21a00e617f45be202
JSON Formatter using ReactJS · GitHub
JSON Formatter using ReactJS. GitHub Gist: instantly share code, notes, and snippets.
🌐
TutorialsPoint
tutorialspoint.com › prettify-json-data-in-textarea-input-in-javascript
Prettify JSON data in textarea input in JavaScript?
Now, I am going to put some bad (unformatted) JSON. The sample JSON data is as follows − · After clicking the button, you will get the following sample output i.e. properly formatted JSON −
🌐
Mantine
mantine.dev › core › json-input
JsonInput | Mantine
import { JsonInput } from '@mantine/core'; function Demo() { return ( <JsonInput label="Your package.json" placeholder="Textarea will autosize to fit the content" validationError="Invalid JSON" formatOnBlur autosize minRows={4} /> ); }Expand code · import { useState } from 'react'; import { JsonInput } from '@mantine/core'; function Demo() { const [value, setValue] = useState(''); return <JsonInput value={value} onChange={setValue} />; }Expand code ·
🌐
JSFiddle
jsfiddle.net › molecule › JNqaX
testing textarea to show stringified json - JSFiddle - Code Playground
The fiddle listings (Public, Private, Titled, etc) will now display latest versions instead of the ones saved as Base versions - this was causing more confusion than good, so we decided to change this long-standing behavior.
Find elsewhere
🌐
GitHub
gist.github.com › wintercounter › ab0f84334f38ce429f18d9dc7bba2c76
Editable react-json-view · GitHub
Save wintercounter/ab0f84334f38ce429f18d9dc7bba2c76 to your computer and use it in GitHub Desktop. Download ZIP · Editable react-json-view · Raw · JsonArea.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Reddit
reddit.com › r/learnprogramming › react: how to build editable json text
r/learnprogramming on Reddit: React: how to build editable JSON text
December 5, 2021 -

Hi!

I am building an app in react, and for that my frontend receives a JSON. I should be able to modify both the values and keys (edit them from the GUI), but also delete some key-value pairs and then send the data back to my server.

I have tried several approaches with various libraries, but nothing works. When i kept it as a key-value pair, i could edit them nicely with react-edittext, but deleting was not working, because editing the key made me lose track of what delete button will delete what pair. So I thought of creating a nested dictionary such as ``````

{'0':{'a' : 'b'}} but i wasn't able to render it properly (i am very new to react). Does anyone have any suggestions on this, please? Any examples or advices? Thank you!

Top answer
1 of 1
3

It's pretty hard in a semantic container to format text to looks like json but you can use a react package like react-json-pretty or you can make a JSON.stringify(json,undefined,2) and pass it in a semantic TextArea that you add into your container and "play" with css to make looks better.
Here an example with both solution:

import React from "react";
import JSONPretty from "react-json-pretty";
import JSONPrettyMon from "react-json-pretty/dist/monikai";
import { Container, TextArea } from "semantic-ui-react";

const ContainerExampleContainer = () => {
  return (
    <>
      <Container>
        <h2>WITH STYLE</h2>
        <JSONPretty id="json-pretty" data={json} theme={JSONPrettyMon} />
        <h2>WITHOUT STYLE</h2>
        <JSONPretty id="json-pretty" data={json} />
      </Container>
      <Container>
        <h2>In a TextArea </h2>
        <TextArea
          style={{
            border: "none",
            cursor: "text",
            width: "100%"
          }}
          value={JSON.stringify(json, undefined, 2)}
          placeholder="json here"
          rows={25}
          disabled
        />
      </Container>
    </>
  );
};
const json = {
  policies: {
    ExtensionSettings: {
      "*": {
        blocked_install_message: "Custom error message.",
        install_sources: ["about:addons", "https://addons.mozilla.org/"],
        installation_mode: "allowed",
        allowed_types: ["extension"]
      },
      "{d634138d-c276-4fc8-924b-40a0ea21d284}": {
        installation_mode: "force_installed",
        install_url:
          "https://addons.cdn.mozilla.net/user-media/addons/950528/1password_password_manager-1.23.1-fx.xpi?filehash=sha256%3A47e9e98f1072d93d595002dc8c221e5cca17e091b3431563a8e3e2be575c5cc1"
      }
    }
  }
};

export default ContainerExampleContainer;



***UPDATE***


Instead of passing a textArea to your Container you can add `as="textarea"` in Container props like this:
 <Container
        as="textarea"
        style={{
          border: "none",
          cursor: "text",
          width: "100%"
        }}
        rows={25}
        value={JSON.stringify(json, undefined, 2)}
        disabled
      ></Container>
🌐
Altcademy
altcademy.com › blog › how-to-render-data-in-reactjs-textarea
How to render data in ReactJS textarea - Altcademy.com
November 6, 2023 - Getting Started In this blog post, we will explore how to render data in a ReactJS textarea. ReactJS, in case you're wondering, is a popular JavaScript library for building user interfaces. In this context, rendering refers to the process of displaying data on the web page. But don't worry if
🌐
CodeSandbox
codesandbox.io › s › json-pretty-textarea-qus7dk
json-pretty-textarea - CodeSandbox
May 28, 2022 - json-pretty-textarea by masoud-naji using json-pretty-textarea, react, react-dom, react-scripts
Published   May 28, 2022
Author   masoud-naji
🌐
GitHub
github.com › uiwjs › react-textarea-code-editor › blob › main › package.json
react-textarea-code-editor/package.json at main · uiwjs/react-textarea-code-editor
A simple code editor with syntax highlighting. Contribute to uiwjs/react-textarea-code-editor development by creating an account on GitHub.
Author   uiwjs
🌐
NGCC in Angular Ivy
iq.js.org › questions › react › how-to-pretty-print-json-with-react
How to pretty print JSON with React?
October 28, 2022 - In this answer, we show you how to use the JSON.stringify() method in React to convert a JSON object into a formatted string that is easy to read.
🌐
GitHub
github.com › nariakiiwatani › react-plain-json-editor
GitHub - nariakiiwatani/react-plain-json-editor: simple(plain) JSON editor for React
// default: JSON.stringify(json, null, 2) deserializer={json => { return JSON.stringify(json, null, 2) }} // format(serialise=>deserialise=>setText) text in the editor after submitting.
Author   nariakiiwatani
🌐
npm
npmjs.com › package › react-json-pretty
react-json-pretty - npm
Actually, react-json-pretty is based on JSON.stringify(value[, replacer[, space]]). However, JSON.stringify(value[, replacer[, space]]) has some optional parameters additionally such as replacer and space. This is also available in react-json-pretty.
      » npm install react-json-pretty
    
Published   Oct 14, 2019
Version   2.2.0
Author   chenckang@gmail.com