The easiest thing to do would be to either use a contenteditable <pre>
element instead of a <div>
, or add white-space: pre
to the <div>
's CSS.
Show stringified json in contenteditable div
-
29-06-2022 - |
سؤال
I was using textarea to display the json in string format, for that I used this
JSON.stringify(this, null, '\t')
To solve some issue in textarea positioning I decided to use contenteditable div. How to show json in contenteditable div as
BusinessUnit : {
"title": "Business Unit",
"type": "Text",
"options": "",
"required": true,
"defaultValue": "1",
"tooltip": "This is a Business-unit",
"unique": true
}
rather than as a showing it as string
BusinessUnit : { "title": "Business Unit", "type": "Text", "options": "", "required": true, "defaultValue": "1", "tooltip": "This is a Business-unit", "unique": true }
المحلول 2
نصائح أخرى
if u have a string Json that name BusinessUnit , u can parse it ilke below
Obj_BusinessUnit= jQuery.parseJSON(BusinessUnit);
var Unique=Obj_BusinessUnit.unique
var Title=Obj_BusinessUnit.title
and so on for the rest of the Properties this is in JAvascript in C# u have to use
JavaScriptSerializer Js = new JavaScriptSerializer();
Channel_info=Js.Deserialize<class>(Json string of the class);
Js.Serialize( an object oa a class to Json String)
Like this?
json = {
"title": "Business Unit",
"type": "Text",
"options": "",
"required": true,
"defaultValue": "1",
"tooltip": "This is a Business-unit",
"unique": true
}
for(var key in json){
$('div').append(key + " : " + json[key] + "<br/>");
}
Or you could do it like this
var p = JSON.stringify(json);
$('div').append(p.replace(/,/g,',<br/>').replace(/{/g,"{<br/>").replace(/}/g,"<br/>}"));
This behavior is built-in to the standard JSON library. All you need to do is:
formatJSON: function(jString) {
return JSON.stringify(JSON.parse(jString), null, 2);
}
It won't unwrap the root property though - that is, your example would be shown like this (note the leading curly brace and the quotes around BusinessUnit):
{
"BusinessUnit" : {
"title": "Business Unit",
"type": "Text",
"options": "",
"required": true,
"defaultValue": "1",
"tooltip": "This is a Business-unit",
"unique": true
}
}
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify for more information.