One might encounter undefined JSON keys when attempting to access them from a script tag

During my attempts to load a specific Json using an Ajax GET request and then parsing it, I encountered an issue when trying to access the Json key from an HTML script tag, as it returned as undefined.

To troubleshoot this problem, I decided to log all the keys of the Json in the console, along with the Json itself. To do this, I implemented the following function:

function getInventory() {
    $.get( "/inventory/", function( data ) {
      var inventoryList = data.split(",, "); // Explanation is provided below
      console.log(inventoryList[0]); // Just testing with the first object
      console.log(Object.keys(inventoryList[0]));
    });
}
getInventory();

Purpose of the `data.split(",, ")` method:

Due to the use of a different programming language in the backend script, I had to transform the output to a format suitable for Javascript. Additionally, there were multiple Json objects, so I separated them using `",, "` and then split them in JavaScript to create a list of Json objects.

After executing the function, the following output was displayed:

https://i.sstatic.net/2RJJa.png

Interestingly, pasting the Json object into the console resulted in a different output, as shown here:

https://i.sstatic.net/LrcXu.png

This discrepancy raised questions about why the script tag did not allow access to the object's keys while manual input in the console did. Could it be that `inventoryList[0]` is not actually a Json object within the script tag? Thank you for any insights!

Answer №1

When calling <code>data.split(), keep in mind that it will return an array of strings instead of objects. In order to convert the JSON string into corresponding objects, you should utilize JSON.parse().

To demonstrate this, consider the following function:

function getInv() {
    $.get( "/inventory/", function( data ) {
      var invList = data.split(",, "); 
      console.log(invList[0]) // Just testing with first object
      var obj = JSON.parse(invList[0]);
      console.log(Object.keys(obj));
    });
}

If you want to parse all items and receive an array of objects as expected, you can use .map() method like below:

var invList = data.split(",, ").map(JSON.parse);

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

Python is unable to convert the input into JSON format, indicating that there is an issue with the bytes input

Currently, I am facing an issue with a specific API endpoint that is triggered when a POST request is made to it. The problem lies in the fact that I am unable to successfully convert the bytes into JSON format in order to access the data contained within. ...

JavaScript is unable to identify one of the JSON values

I am trying to extract the email field from a JSON file using JavaScript. Here is the snippet of code: "contacts": [ { "addedAt": 1332358711001, "vid": 1, "properties": { ...

Incorporate tinyMCE into a colorbox module

Currently, I am facing an issue on my website where there are textareas with tinymce. While I can view all the textareas correctly, when trying to open colorbox within a textarea, it does not inherit the tinymce properties. The code snippet used to open co ...

Using ThreeJS to project a texture onto a mesh surface

I am trying to project a texture onto the surface of a mesh using ThreeJS. The link provided achieves the desired result, although I am uncertain about the method used to accomplish it. . As I continue my research, I will update this post. If anyone has ...

Issue encountered while configuring 'innerHTML' in xmlHttp.onreadystatechange function

Trying to create a JavaScript function that changes the innerHTML of a paragraph within an xmlHttp.onreadystatechange function, I encountered an error in the Chrome Console: Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLH ...

Scrapy generates faulty JSON output

I have implemented the following parsing method: def parse(self, response): hxs = HtmlXPathSelector(response) titles = hxs.select("//tr/td") items = [] for titles in titles: item = MyItem() item['title'] = titles. ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Retrieve the texture's color based on the UV coordinates

Currently, I'm working with version 73 of V. I am dealing with UV coordinates obtained from the intersection of a raycaster and a texture of an object. Is there a way to extract the color (RGB or RGBA) of the used texture at these specific UV coordina ...

What is the best way to set the input type file to null when deleting an image in Vue?

My form allows users to upload an image, and everything was functioning properly until I encountered an issue. When I remove an image and try to upload the same image again, the @change function is not triggered. I am unable to reset the file value to null ...

Error: react-router v4 - browserHistory is not defined

I'm diving into the world of creating my very first React app within Electron (also my first experience with Electron). I have two routes that need to navigate from one to another. Here's the code snippet I am using: Root ReactDOM.render( < ...

Personalizing Material-UI Components using Styled-Components

My attempt to modify the props of a material-ui Grid component using styled-components was not successful. I initially tried: const NavGrid = styled(Grid)` direction: 'row'; ` Unfortunately, this approach did not yield the desired result. T ...

Oops! There seems to be a problem with inserting an image using

I am trying to insert multiple images with a loop when clicked. The images are named "0.jpg","1.jpg","2.jpg" etc. To achieve this, I am using an array with all the elements: {name: '1', result: 1, prefecture: "city", photo1: "0.jpg"}, and my l ...

Having trouble getting req.files to work in a Node.js Express application?

Hello there, I'm facing an issue with accepting an uploaded file. Every time I call req.files, it comes out as undefined. I can't seem to figure out what I am doing wrong... Below is a snippet of my app.js file: var express = require('expr ...

Troubleshooting a mysterious anomaly with a jQuery UI button

Would like to achieve something similar to this: http://jqueryui.com/demos/button/#icons When trying to replicate it, http://jsfiddle.net/p5PzU/1/ Why is the height so small? I expected a square shape but am getting a rectangle instead. What could be c ...

Looking for a script to automate clicking on a specific web element using JavaScript

When working with Selenium, we utilize an action to interact with an element by clicking on it at specific coordinates (X, Y). action.MoveToElement(element, X, Y).Click().Build().Perform() I am looking to achieve the same functionality using Javascript. ...

What is the best way to retrieve the identifier for a specific role?

Struggling to acquire a channel permissions overwrite by obtaining the ID of a role stored in a variable. Any suggestions on how I can access the ID of this new role? This problem has been consuming my time for several days now. I have experimented with t ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Seeking advice on removing the initial blank space from a dropdown value in Angular.js

I have a deeply thought-out logic that I would like to illustrate with an example. However, in order to present it effectively, I am looking for suggestions on how to simplify the process without relying too heavily on the controller. <select class="fo ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

Steps to refresh your nodejs project after making changes

As a newcomer to nodejs, I find myself constantly restarting the server every time I make changes to my HTML files or when using twig, jade, or ejs template engines. Does anyone have any suggestions on how to see these changes in the browser without having ...