How to put a json code in textarea html?

Asked

Viewed 796 times

2

I am developing a page that displays snippets of code in JSON in a textarea, but I have seen on some sites that there is some kind of plugin for this type of display as in the "Errors / Exceptions" tab of this site -> https://m1sandbox.stelo.com.br/ ... would you like to know if there is a plugin or library for this? I thank you!

  • I answered assuming you’re trying to implement with javascript.

2 answers

2

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

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

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

Take 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>

2


You can both use with the <textarea> how much <code> <pre>, in the <textarea> enter the attribute readonly so that characters cannot be removed or inserted, and <code> <pre> add a border to the <pre> to "visually simulate" a <textarea>.

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

Following are 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>Com tag textarea</h2>
<textarea rows="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>

  • Legal brother.. for now in the project the data are statical, I did with code+pre in html, more future I will need, I thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.