Convert JSON object to a string representation

I am attempting to print a JSON object in string format.

(I actually retrieved these data values from Ruby code

var data = '<%=[@pro {|c| {x:c.x, y:c.y}}].to_json%>'
)

When printing the data variable, I noticed that the values contain &quot instead of '

var data=[[{&quot;x&quot;:1,&quot;y&quot;:0}]]

I would like to have the values in the format

var data="[[{ 'x': '1', 'y': '0' }]]";

After removing &quot; using the code

var dataset=JSON.parse(data.replace(/&quot;/g,'"'));
, the output is as follows:

var dataset =[[{"x":1,"y":0}]]

I want to display the values like [[{ 'x': '1', 'y': '0' }]]. How can this be achieved?

Answer №1

If you only have 2 variables, you can easily achieve this by following these steps:

var data = [[{'x': '<%= @pro.x %>', 'y': '<%= @pro.y %>'}]];  

No need to complicate things with the to_json method.

However, if you have multiple values that need to be stringified, you can use the following code snippet:

<% array = [[{'x' => 1, 'y' => 1}], [{'x' => 2, 'y' => 2}], [{'x' => 3, 'y' => 3}]] %>
<%= array.to_json %>

When executed, it will produce the following output:

[[{"x":1,"y":1}],[{"x":2,"y":2}],[{"x":3,"y":3}]]

If you need to send JSON through a request in your controller, you can utilize the following code block:

def send_json_array
    array = [[{'x' => 1, 'y' => 1}], [{'x' => 2, 'y' => 2}], [{'x' => 3, 'y' => 3}]]
    response.headers['Content-type'] = "text/plain; charset=utf-8"
    render :text => array.to_json
end

Answer №2

When using JSON.stringify, an object can be converted into its corresponding JSON representation.

let dataPoints = [{"x":1,"y":0}]
let jsonData = JSON.stringify(dataPoints);

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 steps should I take to make sure my asp.net validators execute prior to invoking client-side javascript functions?

I am facing an issue with my asp.net application which has basic CRUD functionality. I have set up several asp.net validators on a customer details capture page to ensure required fields are filled out. Additionally, I have added a JS confirm box to the sa ...

Struggling with iterating over an Angular array?

I am attempting to iterate through this array. However, I am not seeing anything inside the {{repeat.title}} I am iterating through the array using the following HTML/Angular code: <div class="column inline inline-4 center choice" ng-repeat="repeat i ...

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

I find it curious that Vuejs does not issue a warning when a prop is mutated in a child component. It makes

Recently, I came across an interesting observation regarding prop mutation in Vue 2.6. It is generally advised to avoid mutating props directly in a child component as it can lead to the well-known warning: "Avoid mutating a prop directly since the ...

Create a function that takes advantage of a Promise to resolve its actions

In the asynchronous function provided below: export default async function getUserNames(id: string[]): Promise<string[]> { let userNames: string[] = []; // Additional actions such as service calls are performed here... return userNames; ...

How can we merge two sets of JSON data and display the combined result in chronological order by date?

{"query": {"data":{ "item":[{"title":"some word1", "date":"Sat, 26 Feb 2011 21:02:01"}, {"title":"some word2", "date":"Sat, 26 Feb 2011 17:02:01"}] }}} {"query": {"text":{ "body":[{"title":"some word3", "time":"Sat, 26 Feb 2011 20:22:21"}, {"title":"some ...

I need to obtain both a json and csv file from the provided data

import urllib.request import bs4 as bs source = urllib.request.urlopen("http://www.nhl.com/scores/htmlreports/20172018/TH020070.HTM").read() soup = bs.BeautifulSoup(source, "html.parser") table = soup.table table = soup.find('table') table_row ...

Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function? example: JS FILE: async function getData(){ try { $.getJSON('./data.json', (data) => { return data; }); } catch(error ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

Limiting the input of a user to a maximum of a five-digit integer with a maximum of two decimal points using Angular 2 and ngModel

Currently, I am working on an input text field that utilizes [(ngModel)]. My goal is to restrict users to entering only a maximum of 5 digits with up to 2 decimal places. I believe creating a directive is the best approach to achieve this, however, I am un ...

Locate the unique symbol within an array

I am facing a challenge with validating user input in an input box where alphanumeric values are allowed along with certain special characters. I need to display an error message if the user enters a special character that is not supported by my applicatio ...

Purchasing a Checkbox alongside its corresponding label

I have been working with the Oracle CPQ tool and am faced with the challenge of creating a checkbox attribute within it. Upon inspecting the UI, I came across the following: https://i.sstatic.net/xE5aH.png Upon examining the browser source code (generat ...

How can one retrieve elements from a dictionary array and create a new array?

I'm struggling with how to access elements from a dictionary within an array and create another dictionary in ReactJs. The data structure is as follows: [{name: "dad", data: 10}, {name: "mom", data: 20}, {name: "dad", data: 40}, {name: "mom", da ...

Is it true that the Haskell Text.Json library is capable of reading Rationals but not writing them?

After attempting to parse a JSON file containing a floating point number, I noticed that the Text.JSON package returns the number as a JSRational. This means I can use readJSON on a JSRational. However, I encountered an issue when trying to write rationa ...

Transferring JSON information to database using AJAX

Struggling to send a JSON array via AJAX to a PHP file for database insertion. The jQuery and JSON appear to be working fine, but there seems to be an issue with the values being received on the PHP side, or perhaps the JSON encoding is incorrect. Any sug ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

Unable to retrieve data from JSON file using Ajax request

Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data: { "row":[ { ...

Server side pagination in AngularJS allows for dynamic loading of data

I am currently facing issues with slow application performance when retrieving large data from the database using Spring MVC and REST. I would like to implement server-side pagination in AngularJS to load only a subset of records. Could anyone provide gu ...

Revealing an Angular directive's functionality to a different module

Imagine having a module with a directive structured as follows (this is a rough, untested implementation) There are 3 fundamental requirements that need to be fulfilled: Set up configuration for the element display Add event listeners accessible by the b ...