Access to JS property denied

Here is the JSON data I have:

[
    {
        "_id": {
            "$oid": "560c079e1691682b4ff327ad"
        },
        "year": "2015",
        "month": "9",
        "day": "30",
        "time": "17:02:17",
        "problemDesc": "test",
        "resolution": "test",
        "IM": "test"
    }
]

I'm trying to retrieve the value of year using : console.log(json[0].year) but it returns as undefined. How can I successfully access the year value from this JSON object ?

fiddle :

http://jsfiddle.net/b8dggkof/

Answer №1

When examining the JSFiddle, it becomes apparent that the value contained within json is not a JavaScript Object but rather a string. Therefore, before attempting to access the value, you must first parse this string:

var json = JSON.parse('{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}');

console.log(json[''][0].year);

Once the string has been parsed, you must access the object using an empty string as the key:

json['']

The value associated with this key is an array, and to retrieve the desired information, you must access the first element:

json[''][0]

Finally, you can obtain the year by accessing the corresponding property:

json[''][0].year

Answer №2

To access the inner Object in a JSON string, first insert a key for the JSON and then retrieve the data using that key after parsing it.

var json = '{"key":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}'

console.log(JSON.parse(json)['key'][0].year);

Answer №3

Make sure to convert your json string into a json object using the JSON.parse method, then access the key name, which in this case is an ''(empty string)

var jsonData = '{"":[{"_id":{"$oid":"560c079e1691682b4ff327ad"},"year":"2015","month":"9","day":"30","time":"17:02:17","problemDesc":"test","resolution":"test","IM":"test"}]}';
var parsedData = JSON.parse(jsonData);
alert(parsedData[''][0].year)

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

Tips for adjusting the color of multiple classes that have a common class using a toggle feature

I am working on a simple website using bootstrap 4 and SCSS. I want to include a toggler that switches between dark and light modes on the webpage. However, I'm facing an issue with changing the background color of 6 Bootstrap cards, footer, and the t ...

In Python, unpacking key-value pairs from different layers of a nested data structure, such as a dictionary within a list within a dictionary, allows for organizing the

Scenario: I am currently working on extracting keys and values from a list of python dictionary structures that have been generated in previous steps. These need to be organized into corresponding 'fields' and 'values' JSON arrays, whi ...

Which is the better choice: utilizing object literals or constructor functions?

I'm feeling a bit puzzled about the best way to create an object in JavaScript. It appears that there are at least two methods: one involves using object literal notation, while the other utilizes constructor functions. Is there a specific advantage o ...

ASP.NET - Utilizing Comet to send server messages to multiple clients

I am developing an application that relies on server-side variables which update every second. It is crucial that all clients viewing the webpage are able to see these updates in real-time. Many people have suggested using comet as it allows for pushing/p ...

"Enhance your Rails application with the power of jCrop and

I have successfully integrated jcrop and paperclip to allow image cropping on a separate page (crop.html.erb). However, I am interested in performing all cropping actions on the same page where images are uploaded within a popup div/dialog. Is there a way ...

Encountering a crash issue with JMeter's Selenium Sampler while attempting to click on a button with the Phantom

After building a JMeter Project, I have been utilizing the WebDriver Sampler (Selenium) to monitor response times during interactions with a particular feature on a webpage. To test my project, I have experimented with both Firefox and Chrome Driver confi ...

Two web services are being invoked within a single fragment

In my MainActivity, I have implemented Swipeable Tabs that call two fragments: Fragment A and Fragment B. Each fragment requires data parsing from separate web services using Volley. The issue I am facing is that when I navigate to Fragment A, both web ser ...

Interpreting the Response from Jquery's GetJson Method

I've been facing the same issue repeatedly; I struggle to read the response from a JSON post. For instance $.getJSON('http://gdata.youtube.com/feeds/api/users/live/subscriptions?alt=json', function(data) { $.each(data.feed.entry, functi ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

Oops! TypeScript error TS2740: The type 'DeepPartial<Quiz>[]' is currently missing key properties from type 'Question': id, question, hasId, save, and a few more

I'm struggling to resolve this error. Can anyone provide guidance on what needs to be corrected in order for this code to function properly? import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm& ...

using a different path variable within an href attribute

<a id="m1" class="audio {autoPlay:false, addGradientOverlay:true}" href="MusicFolder/" + document.getElementById("DropDownList1").value + "/" + document.getElementById("DropDownList2").value>document.getElementById("DropDownList2").value</a> ...

Steps on setting the HTTP header "Accept" in a GET request:

I am having trouble retrieving the JSON content using a GET http request. Despite specifying the "Accept" http header in my request, I only receive html/text content. URI uri = new org.apache.http.client.utils.URIBuilder(url) .setParameter("depar ...

Choosing the year and month from the datepicker in Selenium Webdriver: A step-by-step guide

I am attempting to choose the Year and Month from a drop-down menu that appears as a datepicker. I am having trouble selecting it by ID, as it is being selected by class instead. Can someone please provide me with a sample Java code using the JavaScript ex ...

TypeError is encountered while attempting to verify cookies

I created a function like this: const token = req.cookies['SESSION_DATA'] if (token) { ... } catch (err) { ... } However, when I try to check for a token, I receive a TypeError stating "Cannot read property of undefined." Interestingly, the same ...

What is the best way to handle a JSON response once a POJO class has been created for it?

This is a Java class I created to handle JSON parsing. public class TestPojo { @SerializedName("Login Response") private List<com.example.amans.demoparsing.LoginResponse> mLoginResponse; public List<com.example.amans.demoparsing.LoginRes ...

Event that signifies a change in the global state of the Angular 2 router

Is there a universal event that can be utilized for state change/start across all components, similar to the Component Lifecycle Hooks ? For example, in UI-router: $rootScope.$on("$stateChangeStart", function() {}) ...

Successful AJAX Post request functioning exclusively within the Web Console (Preview)

When a user clicks on an element on the website, I have a simple AJAX request to send the ID of that element. However, the script only works in the Web Console under the Network -> Preview section and this issue occurs across all browsers. Here is the ...

Click on the appended text to remove it using Jquery

Seeking a more efficient and streamlined approach for appending and removing appended spans, divs, or text. Below is the code snippet - any insights on what could be improved? /* HTML CODE */ <div id="appendHere" style="padding:10px;border:solid 1px ...

Is there a way to automatically trigger a function once another function has completed its execution?

I am diving into the world of JavaScript as a beginner. All I want to do is trigger the function called seconOne() right after the execution of firstOne(). Specifically, I need the function two to be invoked when the value of p1 reaches 4. While I can us ...

Create a "read more" and "read less" link without using jQuery

For a college assignment, I need to dynamically insert new paragraphs when the "more" link is clicked and remove them when the "less" link is clicked. We are not allowed to use CSS or jQuery for this task. My current code for this functionality is below. T ...