Sending nested JSON in Angular 2 Post Request

Are there any efficient ways to handle the task of importing raw JSON data and posting it to a server using an import function?

For example, if a user copies and pastes the following JSON:

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

I would like all of that information to be sent to the server. However, I am unsure about the best approach to achieve this.

Currently, I have a basic form set up:

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

However, the value displayed for the form is currently:

  "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 need to stringify and then strip the data? What is the best way to convert this back into JSON format?

Answer №1

Take another look at the parsing process:

var formData = { "jsonData": "{\n  \"name\": \"example\",\n  \"details\": [\n    {\n      \"title\": \"sample\",\n      \"notes\": [\n        {\n          \"smallInfo\": \"123\",\n          \"bigInfo\": \"1234567890\"\n        }\n      ],\n      \"scoreMax\": 0\n    }\n  ]\n}" };

var parsedData = JSON.parse(formData.jsonData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality. switchValue: {{ switch }} <br /> <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle> </div> This is how the ...

working with a list of Python objects in a JavaScript environment

Currently, I am building a web application using Flask and Python. In my Python code, I have a class that can be parsed as JSON. class uItem: itemCount = 0 def __init__(self, id, name): self.id = id self.name = name I am trying to acce ...

Exploring the functionality of Typescript classes in a namespace through Jest testing

Within a certain namespace, I have created a method like so: // main.ts namespace testControl { export const isInternalLink = (link: string) => { return true; } } I also have a jest spec as shown below: // main.spec.ts test('sh ...

retrieve the element from a different array using AngularJS version 1

How can I fetch a value from another array? I am using Ionic with Angular 1. In Angular 1, I have created two arrays as shown below: $scope.customers = [{id:1111, name:"Milan Shop", city:"Milan"},{id:2222, name:"Roma Shop", city:"Roma"}] $scope.SizeOfCu ...

Upload an array of choices to the server by utilizing ng-model

I have almost resolved my issue, but now I need help with sending the data to the server. In my current situation, there is a form that includes employee details and projects for that employee (which can be multiple). When the user wants to add projects, ...

Display a recurring list within an Ionic Pop Up

I am facing an issue with a collection repeat list that includes a search bar at the top of the list. When displayed on a real Android 4.4 device, only 9 records are showing up. I have created a codepen example here, where all the records are displayed co ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Tips for successfully implementing Angular.js validation within the confines of a <form> element

Having trouble getting my code to work when I place my app inside the <form name="myForm"> tag. Any suggestions on how to make it function properly? (It works when I place myForm inside ng-app, but my app needs to be within the <form> tag) < ...

What is the best approach to prevent the occurrence of two instances of | async in this particular scenario (version 4.0

Is there a way to achieve the desired outcome in this component without using .subscribe()? I attempted to implement *ngIf="user$ | async as user" but encountered difficulties with it. What is the best approach to create a local variable using user$ | asy ...

Having trouble selecting all checkboxes in Angular

Having issues with selecting all checkboxes in a populated Angular dataTable. I've tried the code below but it doesn't seem to be working. Can you help me find a solution? Please check out the Stackblitz link for a demo. isChecked = false; checku ...

Parsing JSON in PHP to extract individual array values

Recently delving into PHP, I encountered a JSON file that I successfully decoded and stored as shown below: $jsonInput = '[{"b_pag_bo_id":"31","b_pag_user_id":"1","b_pag_id":"1","b_page_mark":"1","b_pag_num":"3","b_pag_note":"","b_page_stop":"1"},{"b ...

Unraveling the mystery of decoding a jwt token

Every time I attempt to validate a user token, I keep encountering Error 500. function verifyToken(req, res, next) { if(!req.headers.authorization){ return res.status(401).send('Unauthorized request') } let token = req.headers.authorization. ...

Angular Universal (Server-Side Rendering) does not pre-render content in specific languages

I have implemented ngx-translate for my multi-language application. app.module.ts import {TranslateLoader, TranslateModule, TranslateService} from '@ngx-translate/core'; export function HttpLoaderFactory(httpClient: HttpClient) { return new ...

The 'Event' type is lacking the specified properties when compared to the 'CdkDragDrop<string[], string[]>' type

After exploring the reorderable columns demo on stackblitz, I came across this interesting code snippet. Specifically, here is the HTML snippet: <table mat-table [dataSource]="dataSource" cdkDropList cdkDropListOrientati ...

Setting up Nginx to support html5mode in your web application involves making adjustments to the

When using AngularJS for clean URLs, I need to implement $locationProvider.html5Mode(true);. However, upon refreshing the page, I encounter a 404 error. I have come across suggestions to configure the server file accordingly. Directory Structure: /html ...

Linking Java and PHP together

I am encountering numerous challenges with PHP and Java Android due to outdated codes that I previously attempted to use in connecting my Android app to a database without utilizing override and JSON. Despite updating to the latest versions, I still stru ...

The focus of the input is lost when the value is being edited, specifically in the case where ngFor and ng

I'm facing an issue with a simple list that binds two-way to a parameter hero in my hero.component.ts. Whenever I begin typing in the input field, it seems to lose focus and I have to click on it again. How can I ensure that users are able to edit th ...

Exploring the capabilities of .map alongside HTTP requests in Angular 2

I'm curious to know if the use of .map is necessary when making API calls with http in Angular 2. Take a look at my code below. It seems to work both with and without .map. If the API returns data, it signals success; otherwise, it indicates an err ...

The index declaration file has not been uploaded to NPM

After creating a Typescript package and publishing it on NPM, I encountered an issue with the declaration files not being included in the published version. Despite setting declaration: true in the tsconfig.json, only the JavaScript files were being publis ...

A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire ...