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

Getting access to UBER's authorize API is a straightforward process that involves following a few steps to retrieve

I have been attempting to retrieve the code from JSON using a specific URL in Postman, unfortunately, I have not been successful in obtaining the code in JSON format. Click here for Uber login Furthermore, when I access this URL in my browser, I am redir ...

Shifting Directive Logic to a Method within a Vue Component

I am currently working with a VueJS component that utilizes the style attribute in the following way: <section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: [& ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Unique identifiers and peculiar symbols for the process of serializing data using flat buffers

I have a Json dataset similar to this: { "!type": "alarm", "$": { "12279": { "!type": "alarm", "title": "Default", "$": { "5955": { "!type": "alarm", "name": "Wake", "day": "SUN", " ...

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

transmit a JSON string to the server using the POST method

I have tested multiple examples sourced from various places but unfortunately, none of them seem to work for me. Every attempt results in an error or a null object on the server side. Below is the client-side code snippet: jsonManual = JSON.stringify(x); ...

Import and access a JSON file from a Git package using Composer

In my current project, I have created a GitHub repository that includes a valuable file data.json. Simultaneously, I am also working on another repository which is the PHP version of this idea. Now, I need to load and parse the list from data.json. Initia ...

Does the size of a JavaScript heap, when it's big but not enough to cause a crash, have the potential to slow down a website, aside from just having an

Utilizing angular material dialog, I have incorporated a mat stepper with three tables (one per step), where one or two of them may contain an extensive amount of records. I have already integrated virtual scrolling to improve performance. However, when ...

Is it possible for an object hidden in the DOM using jQuery to magically reappear when you click the back button or use the bfc

Is there a way to prevent a box from reappearing when using the back button on a webpage? On my website, there is a box that shows up on the first visit. However, when navigating using the back buttons on the site or the browser back button, the box appea ...

Tips for concealing the final click (add) tab after it has been clicked and revealing the hidden (add) button when the user clicks on the remove button

I have created a form where users can add tests. Everything is working smoothly but I want the previous "Add Another Test" field to be removed when the user clicks on it and a new field to be shown. Everything is running well, but the issue is that when t ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

The issue of jQuery POST methods consistently failing

I have set up a Node.js server using Express with a fairly straightforward configuration: var express = require('express'); var app = express(); app.configure(function() { app.use(express.urlencoded()); app.use(express.json()); app ...

View the JSON obtained through AJAX requests

Take a look at the following code snippet: <script type="text/javascript" src="Javascript/json2.js"></script> <script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script> <script type = "text/javascrip ...

Refresh the information displayed in the HTML table

I've been assigned the task of developing a shift management web app to help our current employees track their shifts. The website StaffHub has been suggested as a reference for my web app, and I am currently focused on implementing the calendar featu ...

How can you programmatically deselect all checkboxes in a list using React hooks?

I am facing a challenge with my list of 6 items that have checkboxes associated with them. Let's say I have chosen 4 checkboxes out of the 6 available. Now, I need assistance with creating a button click functionality that will uncheck all those 4 sel ...

Error: The function preciseDiff is not recognized by moment

Encountering an error message: "TypeError: moment.preciseDiff is not a function. I am facing the same issue, wondering if there is a solution or alternative available. I have version 2.24.0 of moment installed. moment-precise-range-plugin In addition, I ...

Using a jQuery UI accordion with a numbered list

As part of my company's user documentation, I am trying to integrate jQuery UI components into our HTML output. Despite my limited experience with JavaScript, I was able to get the accordion feature working for table rows. However, I am now facing dif ...

Ensure both mouse clicks and pressing the enter key are functional for improved accessibility

Consider the following form with a tabindex property: <form id="settings-form"> <input type="text" /> <input type="submit" /> <a href="#" class="cancel-save" tabindex="0">cancel</a> </form> An action is bou ...

Timing of Bindings in AngularJS

In my setup, I have a controller that calls a service to retrieve a list of categories: $scope.enquiryCategories = CategoryServices.listCategories(); The service then fetches this data from an external API: listCategories: function () { return $http({ ...

Scrolling to a specific element using jQuery after a specified delay has

On my website, I have a page with an autoplaying video located at . My goal is to implement a feature where once the video completes playing after a specific duration, the webpage will automatically scroll down to the text section. This scroll action sho ...