Dot notation cannot be applied to JSON objects

I have a function that goes something like this

data = JSON.parse(data)

Initially, data is a string formatted as follows:

"{\"content\":\"Hello there\",\"uid\":\"OoIEfsgabT89EJw\",\"createdAt\":1451586225268,\"user\":{\"avatar\":\"https://avatars.com/123?v=3\",\"login\":\"login\",\"name\":\"Username\",\"uid\":123}}"

After transforming the data, it looks like this:

{"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}}

But when attempting to access data.uid, it returns undefined. What could be causing this issue?

Upon closer inspection of the code:

addItem: function(data) {
  data = JSON.parse(data)

  console.log("Adding: "+data)
  console.log("Adding: "+data.uid)
},

An additional note indicates that the JSON was double encoded. Although parsing the data twice resolved the issue temporarily, it is not the correct solution. How else can this problem be addressed?

Answer №1

If you're starting and ending with double quotes ", this will create a string variable rather than JSON. It's important to use it correctly.

Here is a working example:

var data = {"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}};

console.log(data.uid); //OoIEfsgabT89EJw

And here is an example that doesn't work:

var data='{"content":"Hello there","uid":"OoIEfsgabT89EJw","createdAt":1451586225268,"user":{"avatar":"https://avatars.com/126?v=3","login":"login","name":"Username","uid":123}}'

console.log(data.uid); //undefined

I hope this explanation clears things up for you!

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

The Foundation 6 Zurb Template is not compatible for offline use

After successfully installing Foundation 6 Zurb Template via the cli, I encountered no issues. I then added the missing babel install and everything worked fine online. However, BrowserSync does not seem to work offline. Upon initiating watch, I receive a ...

Enhance your cloud functions by updating data

Recently, I encountered an issue with a function I wrote that interacts with the Real Time Database. Every time I attempted to write data to a specific node, it would add the complete dataset and then promptly delete everything except one entry. https://i ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

End the sessions of all users sharing the identical JWT token

Currently, I am utilizing React and Nodejs while incorporating JWT for user authentication. An issue has arisen where multiple users are simultaneously logged in with the same email address such as "[email protected]". Our objective now is ...

Find the first element in an array of resolved promises in sequential order

In my current setup, I am sending multiple requests to different APIs and each request takes a specific amount of time to fulfill. If one request is successful, I return the resolved value and stop. Currently, I am processing these requests one after the o ...

What is the best way to access a nested promise element in Protractor?

I've recently put together a function in protractor that I'd like to share: function findChildElementByText(parentElement, tagName, textToSearch) { return parentElement.all(by.tagName(tagName)) .then((items) => { items.map( item ...

loading times of Bootstrap-select are slow when used in multiples

I am facing performance issues on my website when I try to include more than 20 select options. The jQuery execution slows down significantly and there is a stop/continue alert, taking minutes to load. Is there any way to optimize the code for faster loadi ...

Issue with Bootstrap alert persisting even after being displayed once

Having trouble with alert messages in jQuery where I display the message, validate data, and then try to hide it again. No errors in the console, even when logging before and after the process. SOLUTION $('#password, #confirm_password').on(& ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

calculating the combined value for each individual day from a JSON file

I'm looking to calculate the total value of NO_OF_CTN for each date, using JSON to obtain the sum value. However, I'm struggling to separate the values for each day in order to prevent them from being summed together. <?php include '../ ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Utilizing ngModel on input elements inside a custom directive, ensuring compatibility with other ng-* attributes

In my current project, I am working on developing a custom directive that acts as a wrapper around an input field. The main purpose of this directive is to simplify formatting, encapsulate animations, and enhance overall functionality. One of my goals for ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

What are the recommended methods for updating data using mongoose?

There are two methods for updating data with mongoose. Using model methods, such as User.updateOne({username}, {$set: {age}}) Finding the document, making changes to its properties, and saving it. Like this: const user = await User.findById(userId) user. ...

Tips for preserving filters or results following filtering with DataTables' searchPane

Utilizing the searchPane extension of DT, which is an R interface to the DataTables library. When constructing a dataTable with a searchPane, the code would appear as follows: library(DT) datatable( iris, options = list(dom = 'Pfrtip', ...

What is the best way to utilize a parent variable in child JavaScript code?

This code utilizes inheritance where the child adds something to the scene that is declared in the parent. How can this be achieved without causing an error when trying to access the scene in the child level? function Parent(domElement, renderStatistic ...

The maximum number of $digest() iterations (10) has been exceeded in $rootScope. Exiting the process

Using UI-Router, I need to check the existing token every time a state change is initiated. The issue only occurs on the initial page load, and disappears upon refreshing the page. Below is the code snippet that I suspect might be causing the error: .run ...

Rotation of objects using Three.js on a spherical surface

I have successfully implemented a particle system to evenly distribute points on a sphere and then place instances of a given geometry on those points. Now, I am looking to rotate those geometries to match the surface angle of the sphere. Below is the cur ...

Clicking on the textarea changes the cursor's position

I've been working on adding an emoji function, but I'm facing an issue. Whenever I select an emoji from the dropdown while having text in the textarea and the cursor placed at the beginning of the text, the emoji always gets added to the end like ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...