What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed.

Here is the string I am working with:

var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01-20,8],[2012-12-28,12]]

To convert it to a JSON object, I use the following code:

var json = eval( JsonData );

But then I receive the following unexpected result in an alert:

1984,787,1985,131,2009,0,1992,8,1972,12

Can someone please provide guidance on how to solve this issue?

Recently, I encountered the following error:

Timestamp: 3/7/2013 1:10:36 PM
Error: TypeError: this.proxy.getTime is not a function

It seems like the error might be related to the incorrect conversion of dates in the JSON object. Can anyone offer advice on resolving this?

Answer №1

Avoid relying on eval()

Opt for using JSON.parse() for converting the string to a JSON object. Additionally, since your JsonData is not in valid JSON format, utilize JSON.stringify() as well.

let JsonData = [[2021-05-15,500],[2021-04-28,250],[2021-03-10,75],[2021-02-20,30],[2021-01-05,15]];
JSONObject = JSON.parse(JSON.stringify(JsonData));

Answer №2

<script>
var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01-20,8],["2012-12-28,12"],["Fri May 04 2012 01:17:07 GMT-0700 (PDT)"]]
var json = eval( JsonData );
alert(json);
</script>

Upon reviewing the data, I discovered that the output shows a mixture of numerical values and date formats without double quotes. To ensure consistency in data handling, it is recommended to enclose all dates in double quotes for clarity and accuracy.

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

When using Loopj to perform a Put or Post request with basic authentication, the response may sometimes be null

In an effort to utilize Loopj for synchronous put and post calls from an HTTP utility class, the code utilizes a synchronous client within an AsyncTask. Certain UI interactions heavily rely on the JSON response, hence the AsyncTask is responsible for man ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

Trigger the reactive helper again when there is a change in the $scope

I am working with a reactive data source in Angular-Meteor and I want to find a method to trigger the reactive function to run again after modifying another $scope value. Specifically, I aim to change the sorting order based on $scope.model.sort: angular. ...

Mapping distinct JSON keys to button components using Javascript/React

I am dealing with the JSON data below: [ {"location":"2034","type":"Residential","price":400000,"address":"123 Fake Street","suburb":"Maroubra","historical_DAs&q ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

Is it possible to pass multiple parameters in one onClick event?

My search bar is located below. Upon clicking the 'search' button, I wish for it to update results and redirect to a different page simultaneously. function SearchBar(props) {   const [innerSearch, setInnerSearch] = useState(""); ...

Guide for bringing in a complete npm library into React Native beyond just a single file access

Currently, I am facing an issue with importing the sjcl library into my project. Even though there are multiple files within the library, I am only able to import one file successfully. This is what I have tried from the command line: npm install sjcl -- ...

JSON data in the RequestBody

Having issues converting JSON to a Java class. Controller @RequestMapping(value = "/{username}/add", method = POST) public void add(@RequestBody NoteModel note) { System.out.println(note.getTitle()); } JSON { title : "Title", te ...

AngularJS, NodeJS, and Mongoose Challenge in Internet Explorer 11

I am currently working on developing my website using the AngularJS framework for the front end, Node.js for the backend, and Mongoose to store data in a MongoDB database. Everything works fine in Firefox RS v.24 and Chrome - when I add a new user to the ...

Receiving the error "Potential null object. TS2531" while working with a form input field

I am currently working on developing a straightforward form to collect email and password details from new users signing up on Firebase. I am utilizing React with Typescript, and encountering an error labeled "Object is possibly 'null'. TS2531" s ...

Generate a dynamic JSON object based on grouped data from a DataFrame by a specified column name

I am currently working on a project that involves creating datasets using the columns of a dataframe. The columns I have to work with are ['NAME1', 'EMAIL1', 'NAME2', 'EMAIL2', NAME3', 'EMAIL3', etc]. ...

The issue with Vue Router is that it fails to display the intended component

I am facing an issue with nested routes in vue-router, specified in the router.js file. After logging in, the Query and Result links in the Header section always display the Register and Login components, even though my Vuex setup seems correct based on my ...

Unable to trigger JSON success

I am facing an issue with my JSON payload as the success function is not triggering. Any help that can be offered would be greatly appreciated. JLS Although I can see the value in the console, the query seems to be working fine but it is not formatted in ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Charting data from MongoDB with Highcharts column chart

Having trouble creating a column chart with Highcharts in Node.js, fetching data from MongoDB. Specifically stuck on the series option - any help is appreciated. Here's an excerpt of my code in the EJS file: <html> <head> <meta ht ...

Using AJAX and JQuery to automatically refresh a webpage on a scheduled interval

I am attempting to automatically refresh a page every 5 seconds with updated data from an SQL Server. Below is my code snippet: @model Test.Data.Domain.ManufacturingCdMachine @{ ViewBag.Title = "Rimage Details"; ViewBag.JobId = Model.CurrentManufa ...

Tips for designing a unique style attribute for your Vue.js component

My goal is to utilize Vue.js without the need for a build step, but I've encountered an issue with its lack of a style property. To tackle this problem, I came up with the idea of creating a custom "style" property on my Vue component instance and dy ...

`Is my JSON contact list missing after running `npm build` in React?`

After creating and deploying my React Web App (NodeJs) online, I noticed that the contact form successfully uploads data to my JSON database using fetch post (localhost:3001). However, when trying to locate the database file after running npm run build i ...

What is preventing the object from being added to the array?

class NetworkManager{ var articleList = [Article]() func downloadJsonData() -> Void{ let jsonUrl = "someOtherUrl" guard let url = URL(string: jsonUrl) else { return } URLSession.shared.dataTask(with: url) { data, respo ...