Parsing an enumerated array of arrays from a string in javascript - javascript

I am using Google charts and am trying to switch out the data using javascript.
The data itself is generated on the server from a SQL database. It is then formatted into a string (I can format this however I want) and given to the browser in response to AJAX requests.
Unfortunately I haven't been able to use JSON to create an array that matches the format used by Google charts. This is an example of the way that I would write the variable if it was being generated directly in javascript: ["United States of America", 7.0287],["Canada", 7.3005],["Australia", 6.8945]
So, this is an array of arrays, and both arrays are enumerated rather than associative. JSON seems to work much better with associative arrays than with enumerated ones.
I've tried using jQuery's parseJSON() function, as well as the JSON2.js library.
var sourceData = '["United States of America", 7.0287],["Canada", 7.3005]';
//(the source data is usually pulled by AJAX, but comes in this format)
var resultArray = new Array();
resultArray = JSON.parse(sourceData); //doesn't work
resultArray = $.parseJSON(sourceData); //doesn't work
Any ideas?

That isn't an array of arrays, this is:
[["United States of America", 7.0287],["Canada", 7.3005],["Australia", 6.8945]]
Without the surrounding [] it's just a syntax error.

var sourceData = '["United States of America", 7.0287],["Canada", 7.3005]',
resultArray = JSON.parse("[" + sourceData + "]");
Working JSFiddle

Related

Extract subset from json in javascript

I would like to substract json entries from the main JSON bulk data, based on an input, in JavaScript. Each entry in the main JSON data has it's own unique ID, but the filter should be based on the text identifier rather than the ID. I would like to retrieve for example all entries that contain the word burg (Burg, BURG, bUrg, etc.) or any other given variety. This should of course also work with other search terms. I do not possess the JavaScript skills to do this.
In the data given below this should return 3 results. Obviously, the result should be the exact same JSON format.
Example JSON:
{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}
Do not use JavaScript for this. Use SQL and its LIKE operator instead.
But if you insist on using JavaScript for this…
Just like HTML, regular expressions cannot fully parse JSON because of serialization.
Filtering after JSON.parse is quite easy however; you can use the Array.prototype.filter() method:
var s = '{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}';
var input = "burg";
var o = JSON.parse(s);
o.features = o.features.filter(e => RegExp(input, 'i').test(e.text));
console.log(JSON.stringify(o));

MongoDB: how to get the last values of two collections in a script?

I am using SpagoBI with MongoDB.
like mentioned in the link [1] I can use script .js on my MongoDB data base to get results.
What I need to do is to merge the two following queries results:
var query1=db['cygnus_/kurapath_enocean_switch2a_enocean'].find().sort({ recvTime : -1 }).limit(1) ;
var query2 = db['cygnus_/kurapath_enocean_switch2b_enocean'].find().sort({ recvTime : -1 }).limit(1);
If I put something like
var query= query1 + query2;
I got the error:
query has no method 'forEach' at serializeResult
Any ideas how to do that?
Thanks in advance for your help!
[1] http://wiki.spagobi.org/xwiki/bin/view/spagobi_server/data_set
Try
var results = query1.toArray().concat(query2.toArray());
What happens here is that toArray() is used to convert the result cursors into standard Javascript arrays of documents (in this case arrays with just one entry because you used limit(1)). Then the standard Javascript array method concat is used to append one array to the other and store it in the new array results.
That array can then be used as you want.

JSON Data format

Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();

suggest me the different options to store this data in javascript

I am getting the data in the following format
[Sl.No, Amount, Transaction Type, Account Number]
[01, $10000, Deposit, 473882829]
[02, $10202, Deposit, 348844844]
[02, $10202, Withdrawal, 348844844]
What is the best way to store this data in Javascript for faster retrieval
var data = ["02", "$10202", "Withdrawal", 348844844]
//empty object
var list = {};
//Constructing the index by concatenating the last two elements of the data.
//Probably this will give the primary key to the data.
var index = data[2] + data[3].toString();
//Store the data using the index
list[index] = data;
You can retrieve the data using the index constructed above.
Determine how the data needs to be accessed. I am guessing it needs to be accessed linearly, so as to not accidentally overdraw (withdraw before deposit), etc -- in this case an Array is generally a suitable data structure. A simple for-loop should be able to find most simple "queries".
Define how the object is represented in Javascript -- is each "transaction item" an array of [x, amount, type, account] or is it an object with the signature {x: ..., amount: ..., type: ..., account: ...} (I often opt for the latter as it adds some self-documentation). It could also be an object created with new TransactionItem (or whatnot) that includes methods.
Determine how to convert the raw data into the chosen object representation. For a well-defined format a simple regular expression or 'split' may work.
Use data. Remember that even a shoddy O(n^2) algorithm is generally "fast enough" for small n. Best to get it working first.
Happy coding.

Scream of the day - Javascript serialising arrays in different ways

This is royally annoying me at the moment:
Consider an array of 2 values:
var myArray = new Array();
myArray.push(21031);
myArray.push(21486);
When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
["21031","21486"]
Now consider an array of a single value:
var myArray = new Array();
myArray.push(21239);
When storing this in a cookie using jquery and toJSON, the value of the cookie looks like this:
21239
This is almost completely useless to me as when I pull the items from the cookie, one comes back as a single value, the other comes back as an array that I can iterate over....ahhh!
Why?
I'd suggest using json2.js' JSON.stringify. It gets both of those cases right:
// [] is the same as new Array();
var foo = [];
foo.push(1);
foo.push(2);
JSON.stringify(foo); // "[1, 2]"
var bar = [];
bar.push(1);
JSON.stringify(bar); // "[1]"
In addition, when you use the json2.js API, your code automatically takes advantage of browser-native functionality in newer browsers.
You're doing something wrong. Regardless of what JSON lib you're using (presuming it actually works), serializing this:
[21031, 21486]
should produce this:
"[21031,21486]"
Not ["21031","21486"] as you've posted. That looks like you're serializing the individual elements. Post more code.
Cookies are strings, so all you are doing is storing a string serialisation of the array. If I do:
document.cookie = [1, 2].toString()
then document.cookie has the value "1,2", which is not an array.
EDIT: as toJSON isn't a native jQuery method, it presumably comes from a plugin. Have you checked the plugin documentation? Alternatively, try a different plugin that works as you expect.

Categories