natyus
natyus

Reputation: 647

how to send a correct json to backend in angular

I am sending an array object which right now looks like this in my console:

[{

}]

but I want to have it like this:

{

}

Could someone tell me how to change it, to my desired form? this is how my documentsArray looks:

  documentsArray = [];

This is how my code looks like this:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result})
          console.log(this.documentsArray)
        }
    }

Upvotes: 1

Views: 180

Answers (2)

Stefano Martini
Stefano Martini

Reputation: 455

JSON specification is this:

[{ array1 }, {array2}, {other arrays}]

And this is the standard whay, why you would like to go outside the standard method?? Please note that in future if you want excange data with oter platforms, you will rebuild everithing, cause json array is with [ ] and json decode will fail if you don't have it, if you don't know how to handle the [ ] just temporary delete the first and the last characters from the writing/reading string, but is not so good..

Upvotes: 0

Remi
Remi

Reputation: 5367

You can access an array item using the index position:

const foo = [{ bar: 'baz' }, { quz: 'qux' }];

console.log(foo[0]); // only first item: `{ bar: 'baz' }`

I.e.:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result});
          // you can use the first object in the array
          console.log(this.documentsArray[0]);
        }
    }

Upvotes: 1

Related Questions