How to put a json code in textarea html?

2

I'm developing a page that shows JSON code snippets in a textarea, but I've seen in some sites that there is some kind of plugin for this kind of view as in the "Errors / Exceptions" tab of this site - > link ... would you like to know if there is a plugin or library for this? Thanks!

    
asked by anonymous 25.08.2017 / 19:08

2 answers

2

You can either use <textarea> or <code> <pre> , in <textarea> enter the readonly attribute so that you can not remove or insert characters, and in <code> <pre> add a border to <pre> to "visually simulate" a <textarea> .

In the JSON part you should apply the JSON.stringify () .

Here are some examples:

var yourObject = {
  "address": {
    "House_Number": 505,
    "Street_Direction": "",
    "Street_Name": "Claremont",
    "Street_Type": "Street",
    "Apt": "15L",
    "Burough": "Brooklyn",
    "State": "NY",
    "Zip": "10451",
    "Phone": "718-777-7777"
  },
  "casehead": 0,
  "adults": [{
    "Last_Name": "Foo",
    "First_Name": "A",
    "Sex": "M",
    "Date_Of_Birth": "01011980"
  }],
  "children": []
};

var textedJson = JSON.stringify(yourObject, null, 4);
document.getElementById("json-area").value=textedJson;
document.getElementById("json-area").readOnly = true; 
document.getElementById("pre-code-area").innerHTML = textedJson;


;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h2>Comtagtextarea</h2><textarearows="20" cols="100" id="json-area">

</textarea>

<h2>Com tag code</h2>
<code >
  <pre id="pre-code-area" style="border: 1px solid #7A7A7A;">

  </pre>
</code>
    
25.08.2017 / 20:12
2

With javascript you can transform a json into texto using the stringify() function, after the conversion included in your HTML normally.

let json = JSON.stringify({"Language":"PT-BR", "TransactionID":"1234567890"});

const codeArea = document.querySelector('.code-area');
codeArea.innerHTML = json;

See the example:

const raw = {"Language":"PT-BR","TransactionID":"1234567890"};
const button = document.querySelector('.button');
const codeArea = document.querySelector('.code-area');
let json = JSON.stringify(raw);


button.addEventListener('click', function(){
  codeArea.innerHTML = json;
});
<code class="code-area"></code>
<button class="button">Click</button>
    
25.08.2017 / 19:24