Why is my TypeScript file mistaking a JSON array for an object?

I'm encountering an issue while attempting to import a large JSON file into a TypeScript file. Despite the JSON clearly being an array, my IDE is throwing an error message stating

Property 'length' does not exist on type '{}'
. How can I resolve this issue?

Here's the code snippet:

TypeScript file:

import cities from "./cities.json"

const printData = () => {
    console.log(cities.length)
}

JSON file:

[
    { "country": "Andorra", "name": "Sant Julià de Lòria" },
    { "country": "Andorra", "name": "Pas de la Casa" },
    { "country": "Andorra", "name": "Ordino" },
    { "country": "Andorra", "name": "les Escaldes" },
    { "country": "Andorra", "name": "la Massana" },
    { "country": "Andorra", "name": "Encamp" },
    ... + 128K more objects
]

It seems that the issue may be related to the size of the file, and it has been suggested to use a .d.ts file to declare it. I attempted the following solution:

let cities: {
    country: string
    name: string
}[]

export declare module "./cities.json" {
    cities
}

However, I now need to reference the object twice as shown below:

import cities from "./cities"

const printData = () => {
    console.log(cities.cities.length)
}

Any insights on how to effectively address this issue would be greatly appreciated. Thank you!

Answer №1

I personally find this method to be quite effective. The only suggestion I have is to modify the way you import the data. Consider destructuring the object during the import process.

Previous Method:

import countries from "./countries"

Updated Method:

import {countries} from "./countries"

By making this change, you will be able to easily access and utilize properties like countries.length without any difficulty!

Answer №2

Utilize object destructuring to extract cities from the object itself. To achieve this in a concise manner, employ the following code snippet.

import { cities } from "./cities";

By doing so, you can utilize just one instance of cities to access its length property!

cities.length;

Implementing this approach will not only resolve your problem but also enhance the clarity of your code.

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

Using Yeoman to embed variables into a JSON file with <%= variable %> without displaying the actual variable

I followed the instructions outlined in the documentation on how to replace values within files: prompting() { return this.prompt([{ type : 'input', name : 'name', message : 'Your project name&a ...

Inserting or changing a key-value pair prior to appending it to an array

Working on restructuring a JSON file to prepare for CSV conversion. The issue lies in the extra layer of nested lists within the JSON structure. The goal is to extract the Unique ID value associated with each data set along with the rest of the informatio ...

Obtain JSON Response Using the Get Method for Coding Complaint Key

Here is the ResponseString that I received: SUCCESS: {"code":200,"shop_detail":{"name":"dad","address":"556666"}, "shop_types : [{"name":"IT\/SOFTWARE","merchant_type":"office"}]} This is my Get request code with headers: func getProfileAPI() { ...

Can multiple parameters be passed in a routing URL within Angular 11?

app-routing.module.ts { path: 'projectmodel/:projectmodelname/salespack', component: componentname} When navigating using a button click, I want the URL to be structured in the following way: I attempted to achieve this by using the following co ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Make MongoDb utilize UUIDs instead of ObjectIds

Is there a way to utilize raw JSON data when storing and retrieving information from MongoDB, without the need to serialize or deserialize it within the service? My goal is to have MongoDB generate "UUID" for the "_id" field instead of ObjectId. For insta ...

Having trouble with Visual Studio 2015 not compiling TypeScript within an ASP.NET Core project?

Seeking assistance with my Angular app development setup in VS2015. Even though it is recognized as a TypeScript Virtual Project, I am facing issues getting the transpiled files into the wwwroot folder within my ASP.NET Core project. Here's an overvie ...

The function UseContext does not exist

Leveraging the context I established, I attempted to implement a basic shopping cart example. However, encountering errors while trying to integrate the functions within my component has left me stumped. As a novice in utilizing the Context API, I would gr ...

In Ruby on Rails, effortlessly passing JSON data from the index action while also rendering a separate application layout at the same time

Having issues with passing @vacancies to json while rendering another layout in my Vacancies controller. The current code isn't working as expected - json is not being passed even though I have specified "wide" layout. When I remove format.html { rend ...

Having trouble fetching JSON data with PHP when the query contains spaces

My Objective I'm working on utilizing the RottenTomatoes API to gather data about a specific movie. For instance, when I search for Frozen, this is the script I use: $q = 'Frozen'; $json_link = 'http://api.rottentomatoes.com/api/pub ...

JSON Countdown will pause when it reaches 0 days

I recently discovered a fantastic countdown feature in SharePoint that I'm utilizing to track the days until a specific date. I have created a calculated column that adds the current date with a set number of days for each task deadline. Currently, th ...

Solving the issue of refreshing HTML Canvas drawings in Vue3 using the Composition API

In my typescript code base, I have successfully created a Sudoku board by directly manipulating the DOM and utilizing an HTML Canvas element with its API. Now, I am looking to elevate my project to a full website and integrate what I have into a Vue3 proj ...

Is there a way to display the items I've added to my cart when I click on it?

I have a collection of product IDs stored in local storage. I am using these IDs to populate the list of products added to the basket. Strangely, when I navigate to the basket page, the products do not appear unless I make a small code modification or re-s ...

Transform a Json string based on query to accommodate varied property names

I came across a Json string that appears like this: {"Linkin Park":{"mbid_id":"f59c5520-5f46-4d2c-b2c4-822eabf53419","artistbackground": [{"id":"34862","url": "http://assets.fanart.tv/fanart/music/f59c5520-5f46-4d2c-b2c4-822eabf53419/artistbackground/ ...

Differences in the way json.dump() behaves on Windows compared to Linux

After developing a Python script to extract data from a website in json form by leveraging the requests library, I save it to a json file. The code was tested on Windows and worked perfectly. However, upon transitioning to a Linux environment, running the ...

RxJs operators prevent the need for multiple subscriptions through the use of looping mechanisms

Currently working on developing a navigation component for an Angular application. The code snippet below shows my current progress. I am looking to avoid the common issue of having multiple subscriptions within each other, known as the multiple subscripti ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...

A step-by-step guide on importing stompjs with rollup

My ng2 app with TypeScript utilizes stompjs successfully, but encounters issues when rollup is implemented. The import statement used is: import {Stomp} from "stompjs" However, upon running rollup, the error "EXCEPTION: Stomp is not defined" is thrown. ...

How can I retrieve an image from a JSON response using Swift 3 and Alamofire?

Is there a way to retrieve an image from JSON using Alamofire and Swift 3? I have successfully extracted data in the form of a dictionary. Below is the JSON response that I received from the API, showcasing the data. While I am able to display textual info ...