Jezyk Danzowki Jezyk Danzowki - 2 months ago 7
JSON Question

Angular 2 submit JSON within JSON

I am trying to use an import function where a user can import raw JSON and then it posts to the server.

for example if a user pastes this json:

{
"name": "testing",
"design": [
{
"name": "test",
"comments": [
{
"short": "123",
"long": "1234567890"
}
],
"maxMark": 0
}
]
}


Then i want all of that to get sent the server.
Not sure the best of way handling such a task though.

Right now i have a simple form:

<modal #importModal [keyboard]="false" [backdrop]="'static'">
<modal-header [show-close]="false">
<h4 class="modal-title">Importing a module</h4>
</modal-header>
<modal-body>
<form name="importForm" [ngFormModel]="importForm" (ngSubmit)="importForm.valid" novalidate>
<textarea class="form-control" rows="20" #data='ngForm' [ngFormControl]="importForm.controls['data']"></textarea>
</form>
<pre>{{importForm.value | json }}</pre>
</modal-body>
<modal-footer>
<button type="button" class="btn btn-danger" (click)="importModal.dismiss()"><i class="fa fa-close"></i> Close</button>
<button type="button" class="btn btn-primary" type="submit" [disabled]="!importForm.valid" (click)="importModal.dismiss() && submitImport(importForm.value)"><i class="fa fa-floppy-o"></i> Submit</button>
</modal-footer>
</modal>


But the value of the form is showing as:

"data": "{\n \"name\": \"testing\",\n \"design\": [\n {\n \"name\": \"test\",\n \"comments\": [\n {\n \"short\": \"123\",\n \"long\": \"1234567890\"\n }\n ],\n \"maxMark\": 0\n }\n ]\n}"


Do i have to stringify it then strip it or ? What's the best of converting that back into JSON?

Answer

Just parse it once more:

var form = { "data": "{\n  \"name\": \"testing\",\n  \"design\": [\n    {\n      \"name\": \"test\",\n      \"comments\": [\n        {\n          \"short\": \"123\",\n          \"long\": \"1234567890\"\n        }\n      ],\n      \"maxMark\": 0\n    }\n  ]\n}" };

var dataObject = JSON.parse(form.data);

Comments