I am trying to update a jqplot chart dynamically with Ajax requests.
My server is returning a string represtation of the data as such:
"[['Juice',30],['Milk',30],['Water',30]]"
However I need to convert this string into an array of arrays.
Is this the correct approach to update the data and if so what is the best way to convert the string.
$.ajax({
url:'http://localhost',
success:function(plotData){
var data = plotData.split(",");
if(plot){
plot.series[0].data = data;
plot.redraw();
}
},
fail:function(error){
alert('error:'+error);
}
});
This code will convert into a one dimentional array:
0: "[['Helpdesk'"
1: "30]"
2: "['Users'"
3: "30]"
4: "['Auto Generated'"
5: "30]]"
You can use eval("var x= " + plotData) as an alternate solution. There are few dangers in using eval, please go through it before using it.
for convertiong a string u possibly could use this function
var plotData = "[['Juice',30],['Milk',30],['Water',30]]";
function strToArr(str) {
//pattern that checks for '[', ']'
var patt=/[\[\]]/gi;
//we replace the pattern with '' symbol
var tmp = str.replace(patt,'').split(',');
var result = []
for (var i = 0; i < tmp.length; i+=2) {
//now all data is in one array, we have to putt in pairs
result[i] = [ tmp[i], tmp[i+1] ]
}
return result;
}
console.log( strToArr(plotData) );
Format your data correctly
It looks like the response you're getting from the server is supposed to be JSON. But, it isn't valid json, and as such is represented as a string.
The change required is very trivial, This is invalid json:
[['Juice',30],['Milk',30],['Water',30]]
This is valid json:
[["Juice",30],["Milk",30],["Water",30]]
The only difference is the quotes. Changing the response string, may (depending on what you're doing server side) correct things immediately such that plotData is already an array of 3 arrays.
Return the right content type
If you are not already serving the response with correct http headers - ensure the response is served as application/json, this of course is in addition to serving a valid JSON string.
Force interpretation as json
To force jQuery to attempt to parse the response as json - you can set dataType explicitly:
$.ajax({
...
dataType: 'JSON'
...
});
I can't remember how strict this is that may work with no server side modifications.
Use JSON.parse
Alternatively, if you just want to handle the string as-is; you could just use JSON.parse:
input = "[['Juice',30],['Milk',30],['Water',30]]";
jsonString = input.replace(/'/g, '"'); // correct quotes as per point 1
result = JSON.parse(jsonString);
result would then be an array containing 3 arrays.
Related
So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply
I have a response with two jsons, exactly like this -
{
"redirectUrl": "http:\/\/lumoslocal.heymath.com"
},
{
"status": "SUCCESS"
}
I need to redirect on getting the response to the redirectUrl. Something like window.location.href = response.redirectUrl. But it's not working. Possibly because of two json in my response. How do I use the 'redirectUrl' of my first json?
My understanding (from the OP's comments) is that the response is coming back as a string like this: authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}'
Technically this is not valid JSON as one big chunk, you'll get an error (test it out below)
JSON.parse('{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}')
To successfully parse the data (and ultimately get the redirectUrl data), follow these steps:
split the string with a comma "," character
parse the "first JSON element"
redirect to extracted redirectUrl
Here's the code for each step:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// 1. split the string with a comma character:
let authArr = authResp.split(',');
// 2. parse the first JSON element:
let redirectObj = JSON.parse(authArr[0]);
// 3. redirect to extracted redirectUrl
window.location.href = redirectObj.redirectUrl;
Or, if you want to parse the entire string into an array of JSON objects you can do this:
authResp = '{"redirectUrl":"http:\/\/lumoslocal.heymath.com"}, {"status":"SUCCESS"}';
// create array of json strings, then parse each into separate array elements
authArr = authResp.split(',').map(e => JSON.parse(e));
// Finally, follow #JackBashford's code:
window.location.href = authArr.find(e => e.redirectUrl).redirectUrl;
If your two responses are in an array, it's simple, even if they're unordered:
var myJSON = [{"redirectUrl": "http:\/\/lumoslocal.heymath.com"}, {"status": "SUCCESS"}];
window.location.href = myJSON.find(e => e.redirectURL).redirectURL;
I have an array of arrays of strings saved in a database column as a varchar:
[["ben"],["john","mike"],["ben"]]
I want to parse the data back into an array of arrays, so I can show the data on the screen. While attempting to do this, I ran into an awkward and annoying problem:
Here's the JSON response that is generated on the server and sent back to the client:
var response = "[{\"Names\":\""+ rows[i].Names + "\"}]";
res.send(response);
Here's the client code I wrote to parse the data:
jQuery.ajax({
type: "GET",
url: ...,
dataType: 'json',
contentType: "application/json; charset=utf-8"
}).done(function(data) {
jQuery.each(JSON.parse(data), function(i, parsedData) {
var names = JSON.parse(parsedData.Names);
var labels = "";
for (var n = 0; n < names.length; n++) {
var label = "<label>" + names[n] + "</label>";
labels = labels + label;
}
console.log(labels);
});
});
This is the error i'm getting:
Here's the JSON validation:
How can I solve this?
There is a simple rule:
Never use string tools to create or modify JSON. No string concatenation (+), no string replace and God forbid no regex.
The only way to produce JSON is to use a JSON serializer on a data structure. And the only way to manipulate JSON is to parse it, modify the data structure, and then serialize it again. JSON itself is to be treated as a constant, for all intents and purposes.
Your server code violates that rule. Change it like this:
var responseData = [{
Names: rows[i].Names
}];
var response = JSON.stringify(responseData);
In the above, responseData is a data structure. You are free to modify it. response is derived from that. You are not free to modify it, the only thing you can do with response is to write it to the client.
Note that rows[i].Names might be JSON itself, so you end up with a double-encoded value in your response.
Provided the server sends the Content-Type: application/json header, the client can use this:
jQuery.get("...").done(function(data) {
// data is already parsed here, you don't need to parse it
jQuery.each(data, function(i, item) {
// item.Names is not yet (!) parsed here, so we need to parse it
var names = JSON.parse(item.Names);
var labels = names.map(function (name) {
return $("<label>", {text: name});
}
console.log( labels );
});
});
If you don't want to call JSON.parse() on the client, you have to call it on the server:
var responseData = [{
Names: JSON.parse(rows[i].Names)
}];
var response = JSON.stringify(responseData);
I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.
when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...