Home > Mobile >  Typescript JSON.stringify, remove key property name
Typescript JSON.stringify, remove key property name

Time:04-12

The following JSON Stringify is not working. I just realized my API Request should look like this without a Key, for api to execute correctly.

{[{"resource":"Providers"},{"resource":"ServiceLocation"}]}. // this is the json request

instead of this with key bootStrapInputList.

{"bootStrapInputList":[{"resource":"Providers"},{"resource":"ServiceLocation"}]}

How do I create a proper header, without a key?

Data Types:

export type BootStrapInput = {
  resource: string;
  query?: any;
};

export type BootStrapResponse = {
  status: number;
  resource: string;
  body: any;
};

Service:

export const getBootstrap = (
  bootStrapInputList: Array<BootStrapInput>,
): any => {
  return kfetch(`/api/BootStrap`, {
    method: 'put',
    body: JSON.stringify({ bootStrapInputList }),
  });
};

// this json stringify creates {"bootStrapInputList":[{"resource":"Providers"},{"resource":"ServiceLocation"}]}

Service Execute:

(async () => {
  let bootStrapList: Array<BootStrapInput> = [
    { resource: 'Providers' },
    { resource: 'ServiceLocation' },
  ];
  const datatest = await getBootstrap(bootStrapList); // this is not working correctly

CodePudding user response:

I think what you actually want is to do the following on service:

body: JSON.stringify({ ...bootStrapInputList }),

That line should result in:

{[{"resource":"Providers"},{"resource":"ServiceLocation"}]}

I saw jsN00b comment and while you said it worked and of course, I believe you and I'm happy you solved it, but doing:

body: JSON.stringify( bootStrapInputList ),

would result in:

[{"resource":"Providers"},{"resource":"ServiceLocation"}]

Which is not the same (no object wrapping the array).

Good luck!

  • Related