In my web application I receive a JSON string from the server which I keep in the greetings variable:
var greetings = '{"2":"hoi","3":"hi","1":"salam"}'
Please notice how the greetings start with the index 2 and the value hoi.
Now I want to parse the JSON and the result is the following:
JSON.parse(greetings) // {1: "salam", 2: "hoi", 3: "hi"}
The order has changed, it seems like JSON.parse orders the result by key.
Is there a way to keep the order of the original string intact?
{
"2":"hoi",
"3":"hi",
"1":"salam"
}
is not an array, its an object. Objects don't have any order.
If the order is important, you need to switch to an actual array.
You generally cannot rely on the order of indices in an object. Use an array of key/value pairs instead.
As you can see the keys are parsed to (numeric) indices, which is why they are ordered that way. You could hack around this by prefixing your keys and then stripping those later:
console.log(JSON.parse('{"i2":"hoi","i3":"hi","i1":"salam"}'))
I have a c# application that converts a double array to a byte array of data to a node.js server which is converted to a Buffer (as convention seems to recommend). I want to convert this buffer into an array of the numbers originally stored in the double array, I've had a look at other questions but they either aren't applicable or just don't work ([...buf], Array.prototype.slice.call(buf, 0) etc.).
Essentially I have a var buf which contains the data, I want this to be an array of integers, is there any way I can do this?
Thank you.
First, you need to know WHAT numbers are in the array. I'll assume they are 32bit integers. So first, create encapsulating Typed Array around the buffer:
// #type {ArrayBuffer}
var myBuffer = // get the bufffer from C#
// Interprets byte array as 32 bit int array
var myTypedArray = new Int32Array(myBuffer);
// And if you really want standard JS array:
var normalArray = [];
// Push all numbers from buffer to Array
normalArray.push.apply(normalArray, myTypedArray);
Note that stuff might get more complicated if the C#'s array is in Big Endian, but I assume it's not. According to this answer, you should be fine.
I managed to do this with a DataView and used that to iterate over the buffer, something I'd tried before but for some reason didn't work but does now.
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));
I have a multi-dimensional array like this:
1 2 3
4 5 6
Now I need to convert this array into a string like 1,2,3;4,5,6.
Can any one suggest how to do this, please?
simply use the join method on the array.
> [[1,2,3],[4,5,6]].join(';')
'1,2,3;4,5,6'
It's lucky that you simply don't have to consider how the apply the join method on the inner lists, because a list is joined by comma by default. when a list is coerced into a string, it by default uses commas to separate the items.
As it was already mentioned by qiao, join() is not recursive.
But if you handle the recursion yourself you should acquire the desired result, although in a rather inelegant way.
var array = [[1,2,3],[5,6,7]];
var result = [];
array.forEach(
function(el){
result.push(
el.join(",")
);
});
result.join(";");
If you need to serialize an array into a string and then deserialize it later to get an array from the string you might want to take a look at JSON:
http://www.openjs.com/scripts/data/json_encode.php
Try this:
array.toString();
See here for reference: http://www.w3schools.com/jsref/jsref_tostring_array.asp
See answer by qiao for a much nicer approach to multidimensional arrays like this.
I am been having trouble counting the number of objects in this array in server-side javascript.
Below is a JSON object which was parsed out using the array that I am trying to count.
NOTE: The object is in object form, not JSON string form.
JSON Object:
[{"dataSymbol":"21135103","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49652777778,"strikePrice":"33.00","last":"1.30","change":"0.20","changePct":"18.1818","lastRaw":1.3,"ask":"1.40","bid":"1.30","lastTime":40073.49652777778,"tick":0,"openInterest":"13.6K","volume":"80311","expDate":40194,"coName":"AJR Jan0 33.0 C"},
{"dataSymbol":"21339645","isHoliday":false,"isIPO":false,"lastTradeTime":40073.50479166866,"strikePrice":"6.00","last":"2.11","change":"0.01","changePct":"0.4762","lastRaw":2.11,"ask":"2.15","bid":"2.10","lastTime":40073.50479166866,"tick":0,"openInterest":"105.00","volume":"62313","expDate":40285,"coName":"EK Apr0 6.0 C"},
{"dataSymbol":"13511861","isHoliday":false,"isIPO":false,"lastTradeTime":40073.489583333336,"strikePrice":"113.00","last":"1.41","change":"-6.34","changePct":"-81.8065","lastRaw":1.41,"ask":"7.60","bid":"7.45","lastTime":40073.489583333336,"tick":0,"openInterest":"805.00","volume":"62975","expDate":40138,"coName":"SPY Nov8 113.0 P"},
{"dataSymbol":"20718334","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49375,"strikePrice":"40.00","last":"1.42","change":"-0.05","changePct":"-3.4014","lastRaw":1.42,"ask":"1.46","bid":"1.44","lastTime":40073.49375,"tick":0,"openInterest":"116.1K","volume":"60470","expDate":40194,"coName":"QQQQ Jan0 40.0 P"},
{"dataSymbol":"20348966","isHoliday":false,"isIPO":false,"lastTradeTime":40073.47708333333,"strikePrice":"41.00","last":"2.39","change":"-0.06","changePct":"-2.449","lastRaw":2.39,"ask":"2.45","bid":"2.42","lastTime":40073.47708333333,"tick":-1,"openInterest":"4.6K","volume":"60320","expDate":40257,"coName":"QQQQ Mar0 41.0 P"}]
I usually use myObject.length to count this type of array, but that is not working.
Response.Write(optionsQuotes.length);
The above code is returning a result of 21339646 as the count, when the actual count of the array is 5.
I would rather not have to loop through the array to count it, because I am looping through it later in order to draw a table, and I need to know the last iteration before the table draw begins.
Any ideas?
EDIT:
//here is where I am gettnig the array of objects...
var myObj = common.getMyObj("param1", "param2");
I serialized the object for the purpose of showing the contents of the array.
myObj.constructor is an Array.
This is on the server side also BTW.
ECMAScript doesn't handle the length of "assocative" arrays like PHP does - either use a real list that has a .length property, set the .length property manually in the JSON as you populate properties in the object, or do a for..in loop and make sure to use .hasOwnProperty and increment some counter.
Mhh... maybe is not a JSON object but an string and the length that is returning is the length of the string and not of the json array
With prototype you need to do something like
var data = '{ "name": "Violet", "occupation": "character" }'.evalJSON();
data.length
but this obviously is depending of the framework that you are using.
The bug must be somewhere else as the following
<script>
var foo = eval('[{"dataSymbol":"21135103","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49652777778,"strikePrice":"33.00","last":"1.30","change":"0.20","changePct":"18.1818","lastRaw":1.3,"ask":"1.40","bid":"1.30","lastTime":40073.49652777778,"tick":0,"openInterest":"13.6K","volume":"80311","expDate":40194,"coName":"AJR Jan0 33.0 C"},{"dataSymbol":"21339645","isHoliday":false,"isIPO":false,"lastTradeTime":40073.50479166866,"strikePrice":"6.00","last":"2.11","change":"0.01","changePct":"0.4762","lastRaw":2.11,"ask":"2.15","bid":"2.10","lastTime":40073.50479166866,"tick":0,"openInterest":"105.00","volume":"62313","expDate":40285,"coName":"EK Apr0 6.0 C"},{"dataSymbol":"13511861","isHoliday":false,"isIPO":false,"lastTradeTime":40073.489583333336,"strikePrice":"113.00","last":"1.41","change":"-6.34","changePct":"-81.8065","lastRaw":1.41,"ask":"7.60","bid":"7.45","lastTime":40073.489583333336,"tick":0,"openInterest":"805.00","volume":"62975","expDate":40138,"coName":"SPY Nov8 113.0 P"},{"dataSymbol":"20718334","isHoliday":false,"isIPO":false,"lastTradeTime":40073.49375,"strikePrice":"40.00","last":"1.42","change":"-0.05","changePct":"-3.4014","lastRaw":1.42,"ask":"1.46","bid":"1.44","lastTime":40073.49375,"tick":0,"openInterest":"116.1K","volume":"60470","expDate":40194,"coName":"QQQQ Jan0 40.0 P"},{"dataSymbol":"20348966","isHoliday":false,"isIPO":false,"lastTradeTime":40073.47708333333,"strikePrice":"41.00","last":"2.39","change":"-0.06","changePct":"-2.449","lastRaw":2.39,"ask":"2.45","bid":"2.42","lastTime":40073.47708333333,"tick":-1,"openInterest":"4.6K","volume":"60320","expDate":40257,"coName":"QQQQ Mar0 41.0 P"}]');
document.writeln(foo.length);
</script>
yields the correct value.
I think you need to eval the string. Could 21339645 be the number of characters?