Extract information from a JSON string and present it on the screen

I am a complete novice when it comes to D3 (with very little experience in JS). Here are the lines of code I am working with:

<script type='text/javascript'> data ='{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16.46,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4"},{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.875,"qsec":17.02,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4 Wag"}';</script>

<script type="text/javascript">
 d3.select("body").append("div").text(JSON.parse(data));
</script>

Every time I run this code, I encounter the following error:

Uncaught SyntaxError: Unexpected token ,     test-html:1

The data itself is generated using R:

<!--begin.rcode results="asis", echo=FALSE, warning=FALSE, message=FALSE
library(RJSONIO)
  out <- paste("<script type='text/javascript'> data ='", gsub("\\[|\\]", "",jsonlite::toJSON(mtcars[1:2,])), "';</script>", sep="")
  cat(out)
end.rcode-->

This results in the JSON string found in the initial code snippet (data).

If anyone can help me identify what the issue might be, I would greatly appreciate it!

Thank you!

Answer №1

the variable 'data' does not contain valid JSON data. Make sure to include [] at the beginning and end of the data.

var data ='[{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.62,"qsec":16.46,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4"},{"mpg":21,"cyl":6,"disp":160,"hp":110,"drat":3.9,"wt":2.875,"qsec":17.02,"vs":0,"am":1,"gear":4,"carb":4,"_row":"Mazda RX4 Wag"}]';

In addition, using JSON.parse(data) will result in 2 separate Objects within the variable data, rather than a single string.

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

What is the best way to style the header of a table when scrolling in CSS?

Currently, I am facing an issue with applying the top CSS property to the thead element of a table while scrolling. I have attempted various methods but have been unsuccessful in achieving the desired outcome. Initially, I used the scroll event, however, ...

The information within the ajax request remains static

I made changes to my ajax data, saved it and even double-checked the file location. However, the old version is still appearing as if it's cached. Here is the original code: function setMessages(roomId, username, message){ $.ajax({ type: ...

Testing a Jest unit on a function that invokes another function which in turn returns a Promise

I have a function that triggers another function which returns a Promise. Below is the code snippet for reference: export const func1 = ({ contentRef, onShareFile, t, trackOnShareFile, }) => e => { trackOnShareFile() try { func2(conte ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Bootstrap 4 experiences issues with modal dialogs

I am experiencing an issue with my code not working on Bootstrap 4. When I click on the 'overview' button, the page darkens but the dialog does not appear. This functionality worked fine with the old version of Bootstrap. Can someone please assis ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

How to eliminate undefined values from a dropdown selection in AngularJS

Blockquote When choosing a material from the column, the first option is showing as undefined. How can I remove undefined from the drop-down list? What changes need to be made in the HTML/JSON data for this to work properly? Blockquote var app = ang ...

Implementing Browser Back or Back button in AngularJS

Currently, I am developing an application that utilizes route methods to navigate between webpages for different modules. Essentially, it is a single page application with route methods responsible for loading the HTML content in the body section. The iss ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

`Loading CSS and JS files in node.js: A step-by-step guide`

I've searched through numerous similar questions without success, so I'm reaching out for help. My folder structure looks like this: Source Code Frontend Graphs.html Graphs.css Temperature.js Server_Backend server.js I aim ...

Displaying a random div using javascript

Seeking a way to display random divs on my webpage, I came across a stackoverflow solution: Showing random divs using Jquery The recommended code can be found here: http://jsfiddle.net/nick_craver/RJMhT/ Despite following the provided instructions, I am ...

Is it true that echo and print are disabled in the 'real-time' version of php?

As a newcomer to programming, I can only describe my script as live, although I know that might not be the correct term. Initially, I developed a bot in php and ran it on xampp locally on my mac, where I could easily print arrays and other content using ec ...

Reducing image file sizes in Ionic 3

I have been struggling to compress an image client-side using Ionic 3 for the past couple of days. I have experimented with: ng2-img-max - encountered an error when utilizing the blue-imp-canvas-to-blob canvas.toBlob() method (which is a dependency of ng2 ...

JavaScript: abbreviated way to selectively append an element to an array

Currently, I am in the process of creating a Mocha test for a server at my workplace. When dealing with customer information, I receive two potential phone numbers, with at least one being defined. var homePhone = result.homePhone; var altPhone = ...

What is the best way to link CSS files from libraries that are downloaded using npm?

For instance, let's say I installed a package: npm install --save package and it gets saved in ./node_modules/package/ Inside that folder, there might be a directory named styles and within that directory, you could find style.css. How can I link ...

Creating JSON lists dynamically in JMeter

Currently, I am utilizing the following Groovy script for handling JSON requests: def oldRequest = new groovy.json.JsonSlurper().parseText(sampler.getArguments().getArgument(0).getValue()) oldRequest.values().removeAll{it.equals('null')} oldRe ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

Is it possible to use CSS to create a gap between the cursor and the placeholder text within an input field?

Could you please assist me with a bug I have encountered on an older version of Firefox for OSX (37.0.2)? I have included a screenshot of the issue here: Is there a way to use css to move the first character of the placeholder text away from where the cur ...

Having trouble adding global method using Plugin in Vue 3?

I have been working on creating a method that can generate local image URLs to be used in any template automatically. However, I encountered an issue while trying to develop a plugin that adds a global property. Plugin Implementation: // src/plugins/urlb ...