ControlAltDel
ControlAltDel

Reputation: 35106

Formatting JSON in a textarea

I have a page where I want to let the user edit an application - stored in a JSON. It looks like this:

{"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":[]}

I am setting this using

var pattern = ",", re = new RegExp(pattern, "g");
  casedetails.innerHTML = JSON.stringify(apps[0]).replace(re , ",
");

The problem is after I make changes, the first time I run this, the textarea doesn't show the newlines - even though they are there! (If I copy/paste they show up). If I refresh it shows the newlines.

Can anyone help me figure out how to get JSON on new lines without having to refresh? I am using IE 9

Thanks!

-Tom

Upvotes: 1

Views: 13645

Answers (1)

Medioman92
Medioman92

Reputation: 581

this should be pretty simple... take a look if this jsFiddle fit your needs

   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,undefined, 2);
document.getElementById("json-area").value = textedJson

;

P.S. i've used jQuery just to speed-up the example but the function on which you should focus is JSON.stringify

Upvotes: 9

Related Questions