I have a js variable that contains an object. I'm passing the data in that object to a html <textarea>
using jquery. I'm also passing my variable through JSON.stringify
so the code looks like so:
$("#textarea1").val(JSON.stringify(myVarData, null, "\t"));
The problem is twofold.
<textarea>
the data is enclosed in curly brackets {}
as it's still in JSON - How can I remove them before sending it to the <textarea>
? Basically plain text.The data is well formatted as
{ "property":value,
"property":value,
"property":value }
which is okay if I had simple data, but in one of the properties, I have a value that looks like so:
"report_data":"{"subjects":[{"subject_name":"ENGLISH","parent_subject_name":null,"teacher_id":39,"initials":"A.A.F","use_for_grading":true,"marks":{"MID-TERM 1 2018":{"mark":87,"grade_weight":100,"grade":"A"}},"overall_mark":"87","overall_grade":"A","remarks":"Excellent"},{"subject_name":"MATHEMATICS","parent_subject_name":null,"teacher_id":40,"initials":"B.K.K","use_for_grading":true,"marks":{"MID-TERM 1 2018":{"mark":80,"grade_weight":100,"grade":"A"}},"overall_mark":"80","overall_grade":"A","remarks":"Excellent"},
How can I get this value
data formatted to be easily readable like in (1) above? Is it possible to choose only what I want from the value
? I tried using JSON.parse
after the stringify
but got [object Object]
as the result.
NOTE This isn't a duplicate of this as that question is about copying an object to a text box. In part one of my question - I want the data out of the curly brackets - which is no longer JSON. And that solution proposes what I'm already using.
var a = {"report_data":{"subjects":[{"subject_name":"ENGLISH","parent_subject_name":null,"teacher_id":39,"initials":"A.A.F","use_for_grading":true,"marks":{"MID-TERM 1 2018":{"mark":87,"grade_weight":100,"grade":"A"}},"overall_mark":"87","overall_grade":"A","remarks":"Excellent"},{"subject_name":"MATHEMATICS","parent_subject_name":null,"teacher_id":40,"initials":"B.K.K","use_for_grading":true,"marks":{"MID-TERM 1 2018":{"mark":80,"grade_weight":100,"grade":"A"}},"overall_mark":"80","overall_grade":"A","remarks":"Excellent"}]}}
console.log(JSON.stringify(a).replace(/[\[\]']+/g,'').replace(/[\{\}']+/g,''))
var final = JSON.stringify(a).replace(/[\[\]']+/g,'').replace(/[\{\}']+/g,'');
$("#textarea1").val(JSON.stringify(final, null, "\t"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id = "textarea1"></div>
</body>
</html>
The fast and optimized solution can be using regular expression
.
No need to even loop here
just use,
JSON.stringify(myVarData).replace(/[\[\]']+/g,'').replace(/[\{\}']+/g,'')