The program was expecting an array to start, but instead encountered an object. Any suggestions on how to convert

{
    "workingHours":
        [
            {
                "date":"2023-02-01",
                "amount":3,
                "freigegeben":false
            }
        ]
}

Whenever I include this in my request Body, I encounter the error mentioned in the title. How can I manually change the format to make it an Array by adding [ and ], or what other solutions could I explore?

Below is the request I am sending:

public async saveWorkingHours(
    employeeId: string | null,
    workingHours: WorkingHours[]
  ): Promise<boolean> {

    var result = Object.entries(workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })));
    try {
      await this.httpService.fetch(
        `${this.apiUrl}employees/${employeeId}/workingHours`,
        HttpMethod.PUT,
        {

          // The issue lies in the body starting with "{", instead of "[". 
          workingHours: workingHours.map(wh => ({ ...wh, date: this.dateService.format(wh.date) })),
        }
      );
      return true;
    } catch (e) {
      console.error(e);
      return false;
    }
  }

Definition of Workinghours interface:

export interface WorkingHours {
  date: Date;
  amount: number;
  freigegeben: boolean;
}

Converting the format:

 var convertedFormatData = [];

    var tempObj = {
      workingHours: workingHours.map((wh) => ({
        ...wh,
        date: this.dateService.format(wh.date),
      })),
    };
    convertedFormatData.push(tempObj);

The resulting output appears as shown below:

{"convertedFormatData":[{"workingHours":[{"date":"2023-02-01","amount":3,"freigegeben":false},{ ...

Answer №1

The signal for starting an array is BEGIN_ARRAY which is represented by [, while BEGIN_OBJECT is indicated by {.

If you begin with {, the website may interpret it as an object instead of a list. To send a list, it should look like this:

[
   {
       "example": "json data"
   }
]

Therefore, in your case, the correct format would be:

[
   {
      "workingHours":[
         {
            "date":"2023-02-01",
            "amount":3,
            "approved":false
         }
      ]
   }
]

There are multiple methods to convert it into an array:

var example = {
  "workingHours":[
     {
        "date":"2023-02-01",
        "amount":3,
        "approved":false
     }
  ]
};
console.log(example["workingHours"]);

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 issue with Vuex and Typescript is that when using mutation object payloads, they are consistently undefined

Every time I run my code, the object payload I'm passing as a secondary parameter to my Vuex mutation method ends up being undefined. Both my Vuex and component files are coded in TypeScript. When looking at my index.ts file for my Vuex store (where ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

Replacements of JSON null values within Mantle

Utilizing Mantle for parsing JSON data, the typical structure includes: "fields": { "foobar": 41 } However, there are instances where the value of foobar is null: "fields": { "foobar": null } This leads to an exception being thrown ...

"Unraveling the country code from a number in PHP:

What is the best way to extract country codes from a phone number in PHP? I am looking to validate a country based on 1-3 characters from the number. I have an array mapping ( code => country), and I currently have a script that works for single charact ...

String Representation of Android View IDs

As I work on creating a Class that will populate my layouts with data from a JSON Schema, I am encountering a challenge. The JSON includes definitions such as { type: "checkbox", label: "Label text", value: true, id: "liquids" }. While rendering the UI is ...

The attempt to make an HTTP request to the Logic app results in an error message stating that "Property selection is not enabled for values of the type 'String'"

I have a simple logic app set up to perform a task, with an HTTP trigger that expects a JSON object. To call this logic app trigger from C#, I use the following code: var postData = new QERestartModel { AppName = appname, ...

The JSON response generated by the C# ServiceContract is not quite what I was anticipating

Currently, I am utilizing a service contract as an API with a particular interface declaration: namespace MyAPI { [ServiceContract(Namespace = "http://MyAPI")] public interface IMyAPI { [OperationContract] [WebInvoke(Method = " ...

Is it advisable to move operations outside of the useEffect hook?

Is it advisable to move code outside of the useEffect function in React? function BuyTicket(props: any) { useEffect(() => { //.. }, [eventId, props.history]); // IS IT RECOMMENDED TO PUT CODE HERE? const userNameL ...

Retrieve values from DynamoDB in their original Number or String formats directly

Here is the code I am using to retrieve data from DynamoDB. async fetchData(params: QueryParams) { return await this.docClient.send(new QueryCommand(params)); } const dbObject: QueryParams = { TableName: process.env.TABLE_NAME, KeyCo ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

My Twitter feed is no longer displaying using JSON

Recently, I've encountered an issue with my Twitter code not working properly. Could it be due to changes in Twitter's API? If so, does anyone have suggestions on how to troubleshoot and fix the code below? Appreciate any assistance, Osu JQTWE ...

Here's a way to resolve the issue: ReactDOM.render() - TS2345 error: Cannot assign type '() => Element' to type 'ReactElement' in the argument

After tackling React-Router with Typescript, I encountered a typing issue that has me perplexed. Prior to this, I was using an older version of React and React-Router. But now, after updating to the latest builds using yarn, I'm facing this hurdle. ...

PHP Code: How to Retrieve JSON from a Remote URL

Looking for some help with decoding a JSON file. Here's the link to the file: I've been trying to decode it using PHP like this: $json = file_get_contents('http://www.jeewanaryal.com/angryQuiz/eighties/json/eighties.json'); $data = j ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

Using JSON Filtering with React

I am currently working on fetching JSON data and implementing a filtering feature for the displayed content. An error that I am encountering is: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Any insights on what might be ...

Creating a dynamic form that allows for looping through an array of form submissions to efficiently insert data into

I am facing a challenge with a dynamically built form: foreach($xml->config->popup as $popup_item){ <input class="fm-req" id="fm-popup_name[]" name="fm-popup_name[]" type="text" value="" /> <textarea class="fm-req" rows="4" cols="5 ...

Emphasize a word in a Typescript text by wrapping it in an HTML tag

I've been experimenting with using HTML tags within TypeScript to highlight specific words in a sentence before displaying the sentence in HTML. Despite searching on StackOverflow for various solutions, I haven't been able to find one that works. ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

"Creating a dynamic TreeList in Ignite UI by linking pairs of names and corresponding

I recently developed a drag and drop tree list inspired by the tutorial on IgniteUI website. The main tree list functions properly, but I encountered an issue with the child nodes displaying as undefined, as illustrated in the image below: https://i.sstat ...