Having trouble understanding JSON and Arrays in TypeScript

When extracting data from the database using Sveltekit and Node.js, I always fetch data in the following way:

...
responseData = await response.json();

The retrieved data is an Object, which can be assigned to an array like this:

let getData = [];
getData = responseData ;

I find it confusing that when the returned JSON Object is displayed in the console, it shows brackets indicating an array (though when checked with typeof, it is classified as an Object):

[
 {a:1,b:1},
 {a:2,b:2},
]

I would expect a JSON Object to look like this:

{"name":"John", "age":30, "car":null}

and why can a JSON Object be directly assigned to an array?

It seems like there might be some misunderstanding about these data types on my end.

Answer №1

When you await response.json(), the resulting type is currently defined as any. This essentially tells TypeScript to not worry about the type, allowing you to assign any value to a variable of type any and even assign a value of type any to a variable of any other type, which can be unexpected. In such cases, it's recommended to use the type unknown and explicitly cast unknown values to another type before manipulating them.

The result of typeof [] is "object", so using typeof alone cannot distinguish between arrays and objects. Instead, use Array.isArray(x) to check for an array. It's important to note that typeof null also returns "object", which may come as a surprise.

Although JSON being an array at the top level is valid, it is generally preferred to avoid accepting any JSON-compatible value - such as strings and numbers - as the top-level value in most contexts.

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

Is there a potential issue in Next.js 14 when utilizing the "useClient" function alongside conditional rendering in the app/layout.tsx file?

Within my app, there is a Navbar that will only be visible when the route is either "/" or "/teachers". The Navbar will not appear on the dashboard page ("/dashboard"). I achieved this using conditional rendering in the app/layout.tsx file. "use clien ...

Converting a List to an Array in Android: A Step-by-Step Guide

Hey everyone, I have a question regarding an application that is consuming data from an ODATA service in SMP server. I am fetching the data as shown below: public class callService extends AsyncTask<Void, Void, ArrayList<String>> { ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Decoding unidentified JSON object types using AutoBean on Google Web Toolkit

On my server, JSON is used to return a list of objects which could be anything from Cats to Dogs. It's easy to work with the AutoBeanCodex when I know they are all Cats. But when the types are unknown, what should I do? Adding a type field to each e ...

The issue of appending request URLs in the $.ajax function

Can anyone explain why jQuery.ajax() adds a parameter to the URL? I enabled cache, but it's still not working as expected. The console logs are not showing up and the request URL is being modified with &_=1396146406542. How can I remove this add- ...

Run TestNG from the Windows Command Prompt

Encountering an issue while trying to run testNG in CMD prompt. The error received is: java.lang.ClassNotFoundException: com.google.gson.JsonObject I have ensured that all the necessary jar files are included in my build path. This includes gson-2.8.2 ...

What benefits does Observable provide compared to a standard Array?

In my experience with Angular, I have utilized Observables in the state layer to manage and distribute app data across different components. I believed that by using observables, the data would automatically update in the template whenever it changed, elim ...

Importing the isPropertyUpdated method in Angular 4

My challenge lies in utilizing the isPropertyUpdated function within Angular 4. However, I have encountered a roadblock as Angular 4 does not facilitate deep imports. An example of an import that fails to work on Angular 4 is: import {isPropertyUpdated} ...

What is the best way to refine React Component's props with Typescript?

My setup involves utilizing two specific components: Test and Subtest. The main functionality of the Test component is to provide visual enhancements and pass a portion of its props down to the Subtest component. Some props in the Subtest component are des ...

Creating a 2D grid array using data from a different source

I'm working on generating a 2D grid with random numbers, and then creating another grid of the same size with -1s in place of numbers that are evenly divisible by 3. I've completed most of the code, but the second grid is only displaying -1s. Can ...

What is the best way to create dynamic series data for highcharts?

I have integrated angular-highcharts into my project and utilized this column chart from https://www.highcharts.com/demo/column-basic for visualizing my data. Below is the format of my data: [ { "project": "train project1", ...

What is the best way to incorporate a JSON file into a JavaScript class?

I attempted to load a JSON file within a JavaScript class, but encountered an issue where the loaded data was only accessible inside a specific function. class CreatePage { constructor() { var request = new XMLHttpRequest(); request. ...

Using JSON to selectively serialize object properties

I have a specific object named MyObject with various properties. By using a Linq query, I populate MyList with instances of MyObject before serializing it into JSON format. As a result, I get something like this: List<MyObject> MyList = new List< ...

transferring elements from an array to strcmp

I'm currently working on a task that involves breaking down user input into parts using whitespace as a delimiter, storing these parts in an array called tokenAr, and comparing the first part (tokenAr[0]) to see if it matches with sHistory. If there i ...

Custom TailwindCSS Theme Builder

My goal is to implement a variation of themes and be able to switch between them using tailwind CSS. I came across a tutorial on YouTube regarding this topic in JavaScript youtube video, but I am working with TypeScript and encountering issues with a cus ...

Using GSON for JSON deserialization in Java

My data is represented in Json format {"0x3b198e26e473b8fab2085b37978e36c9de5d7f68":{"usd":541.56},"0x54523d5fb56803bac758e8b10b321748a77ae9e9":{"usd":0.059097},"0x330540a9d998442dcbc396165d3ddc5052077bb1": ...

Ways to divide a string into pairs of two using jQuery

I have a variable containing a string with exactly 44 characters: 02081516171821242936374750565865666871737476 I want to split it into an array in the following format: arr[0]=02 arr[1]=08 . . arr[21]=76 Can someone help me achieve this? Thank you. UP ...

"Encountering a 406 Not Acceptable error while trying to return JSON data

I am currently developing an application that will solely function as a RESTful service, with JSON responses being returned. Using Spring MVC and following the guidelines outlined in this article: I have included the Jackson jar in my POM file, enabled r ...

Trouble with Playwright test loading local URL

I'm encountering difficulties with the homepage loading in my application, despite having what I believe to be correct configurations. The test and playwright config are as follows: example.spec.ts import { test, expect, chromium } from '@playwr ...

Encapsulation of JSON data with variable declaration

After generating a json data using the PHP code below: $index = array(); foreach($rows as $row) { $row['data'] []= (object) []; $index[$row['cat_id']] = $row; } // build the tree foreach($index as $id => &$row) ...