Is it possible to access JSON with a numeric key and receive undefined as a result?

I've been attempting to extract information from my JSON data, but I keep getting an undefined result.

Here is a snippet of my JSON:

{
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "E",
    "6": "F",
    "key":"pair"    
}

This is how I'm parsing the data:

rawdata = fs.readFileSync('data.json');
data = JSON.parse(rawdata);
console.log(data.1) //returns undefined. I even tried converting 1 to a String with no luck.
console.log(data.key) //outputs pair

Answer №1

If a property of an object starts with a number, you cannot access it using dot notation.

To retrieve the value of such a property, you must use square bracket notation instead:

let obj = JSON.parse(`{
    "1": "A",
    "2": "B",
    "3": "C",
    "4": "D",
    "5": "E",
    "6": "F",
    "key":"pair"    
}`);

console.log(obj['1']);

Answer №2

When using dot notation to access a value, it is important that the property key is a valid identifier

To clarify, the property in this code needs to be a valid JavaScript identifier, which consists of alphanumerical characters, underscores ("_"), and dollar signs ("$"), and cannot begin with a number. For example, object.$1 is acceptable, but object.1 is not.

If needed, bracket notation can also be used like so:

obj['1']

You can find more information in the Property Accessors section of the spec

Answer №3

If you want to access the content of a JSON file in your code, you can use the following line:

const data = fs.readFileSync('./data.json');
This command assumes that the data.json file is located in the same directory as your script. After reading the file, you can retrieve specific values using .data['1'].

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

When attempting to use focusin/focusout, I encountered the following error: Uncaught TypeError - The property 'addEventListener' cannot be read from null

When attempting to utilize the DOM events focusin/focusout, I encountered an error: Uncaught TypeError: Cannot read property 'addEventListener' of null. The issue seems to be originating from main.js at lines 18 and 40. I am using Chrome as my b ...

What is the best way to extract words from a string within a textarea using javascript?

Currently, I am focused on improving my skills in JavaScript and HTML. In one of my projects, there is a text area where the user inputs a CSV format like this: 17845 hello bye 789 After input, I get 17845,hello,bye,789. Now, the challenge is t ...

Jackson Parser: skip deserialization when encountering a type mismatch

When I receive a response from the server through cakephp, it looks like this: [ { "id": "42389", "start": "0000-00-00", "end": "0000-00-00", "event_id": null, "trip_id": "5791", "location_id": "231552", "user_id": "105", "users_attendin ...

Using Node to parse XLSX files and generate JSON data

Hello, I am currently utilizing the js-xlsx package which can be found at this link. My inquiry is how to successfully parse an xlsx file with merges and convert it into JSON format. You can view what the excel sheet looks like here. Ultimately, the JSON o ...

When the mouse is moved, display a rectangle on the canvas

I am having an issue with drawing a rectangle on canvas. The code below works fine, except that the path of the rectangle is not visible while the mouse is moving. It only appears when I release the mouse button. Any assistance would be greatly appreciate ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

Sorting through arrays in JavaScript/React

My search functionality works well, but I'm facing an issue when the item is not found in the array. I attempted using objects.Keys to handle this situation, but it's displaying on render instead of when the book is not found as expected. Should ...

The default value is not displayed in the Angular dropdown menu

When using regular html select menus, if you create an option element with selected and disabled attributes and provide text for that option, the text will be displayed by default in the select menu. Below is a basic example of HTML code: <select name= ...

Having trouble getting a button's OnClick event to work with Bootstrap on iOS devices

Here is an example of the issue I'm experiencing: http://jsfiddle.net/d01sm5gL/2/ The onclick event functions correctly on desktop browsers, however when using iOS8, the event does not trigger. I have tried calling the function manually through the d ...

Discovering the Keys of a Multidimensional Array in JSON with AngularJS

I'm attempting to create a form using a JSON array. I want to display the keys in the HTML. Check out this example array: { "Fred": { "description": "A dude" }, "Tomas": { "description": "Another Dude", "Work": { "Current" ...

My program contains redundant sections that are being repeated multiple times, and I am unsure of how to remedy this issue

This particular payment gateway relies on a paid market for processing transactions. Unfortunately, there seems to be an issue where multiple error messages are being triggered during the payment verification process. The errors include: ❌ | An error h ...

How is UI Router Extras causing unexpected errors in my unit tests?

QUESTION: - I am facing failures in my tests after installing ui-router-extras. How can I resolve this issue? - Is there a way to use ui-router-extras without causing test failures? If you want to quickly install this, use yeoman along with angular-full ...

Sending JSON data from an Android client to a WCF service for storage in a SQL Server 2008 database

I've encountered an issue while trying to post data through a WCF service. The service is hosted and functioning correctly with my .NET website, but for some reason, it's not working with my Android client. I'm having trouble understanding t ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

When the response is anything other than a String, the afterCompletion method of the HandlerInterceptor interface is executed prior to the response being completely committed

While troubleshooting an issue, I encountered a peculiar situation in my Spring Boot application. I have a GET REST endpoint that returns a specific POJO: @GetMapping(value = "/dto", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseE ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Contrary to expectations, the middleware EJS fails to render JPG files at

I am currently working on a NodeJS server using EJS. The goal of this server is to render an HTML page that contains a line of text and a jpg file. However, I am encountering an issue with the jpg file not being loaded by the server. Even though I have sp ...

JavaScript nested function that returns the ID of the first div element only upon being clicked

I am facing an issue with a function that returns the id of the first div in a post when an ajax call is made. The problem is that it repeats the same id for all subsequent elements or div tags. However, when the function is used on click with specified ...