Prevent JSON.parse from rearanging an object - javascript

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"}'))

Related

How to Convert string of multiple object to in array with different keys

I have a string to multiple objects and I need to add this object in an array with different values. This data received from the cart so object can be 2,3,4...
exmaple:
{"hidden_product_name":"productA","productId":"120","product_sku":"","quantity":"2","hidden_unit_price":"500","hidden_total":"1300","total_pr_price":"1000"},{"hidden_product_name":"productB","productId":"127","product_sku":"","quantity":"1","hidden_unit_price":"300","hidden_total":"1300","total_pr_price":"300"}
this is a full string of two objects and I want the output like this.
Desire output:
[{"hidden_product_name":"productA","productId":"120","product_sku":"","quantity":"2","hidden_unit_price":"500","hidden_total":"1300","total_pr_price":"1000"},{"hidden_product_name":"productB","productId":"127","product_sku":"","quantity":"1","hidden_unit_price":"300","hidden_total":"1300","total_pr_price":"300"}]
How can I do this please help...
I found the best and easiest way to resolve this problem...
data = '{"hidden_product_name":"productA","productId":"120","product_sku":"","quantity":"2","hidden_unit_price":"500","hidden_total":"1300","total_pr_price":"1000"},{"hidden_product_name":"productB","productId":"127","product_sku":"","quantity":"1","hidden_unit_price":"300","hidden_total":"1300","total_pr_price":"300"}';
data2 = '['+data+']';
then data2 will return:
[{"hidden_product_name":"productA","productId":"120","product_sku":"","quantity":"2","hidden_unit_price":"500","hidden_total":"1300","total_pr_price":"1000"},{"hidden_product_name":"productB","productId":"127","product_sku":"","quantity":"1","hidden_unit_price":"300","hidden_total":"1300","total_pr_price":"300"}]

convert array stored in a string to an array

I have an array value which is coming from database as an string. I need to convert it into an array. When I check my value in console I can see value as
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
In order to perform my operations I need it to be in below structure
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
I have already tried JSON.parse() and parseJSON
Expected Result :
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
Actual Result :
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
You need to remove the outer quotes from your string, then pass the value to JSON.parse() to get the array.
Also, you have to quote each item correctly, "space should be "space".
You can sanitize the string with String.prototype.replace() (assuming the quoting of space has been fixed in the DB):
const data = '"[["COL1","COL2","COL3"],["COL4","space","COL5"]]"';
const dataSanitized = data.replace(/^"|"$/g,"");
console.log(JSON.parse(dataSanitized));
I would suggest you do parse
JSON.parse('[["COL1","COL2","COL3"],["COL4","space","COL5"]]')
i would not suggest eval as i just read an article about "how eval is evil"
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Converting an array to a string in Javascript

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.

Javascript Counting Array of Objects

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?

JSON conversion in javascript

I'm trying to stringify a multi-array variable into a JSON string in Javascript. The
//i'm using functions from http://www.json.org/json2.js
var info = new Array(max);
for (var i=0; i<max; i++) {
var coordinate = [25 , 32];
info[i] = coordinate;
}
var result = JSON.stringify(info);
But result doesn't look like a JSON string at all. What am I doing wrong here?
You, and many in this question, are confused about the JSON specification. The string you have is a valid JSON array.
From json.org
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record,
struct, dictionary, hash table,
keyed list, or associative array.
An ordered list of values. In most languages, this is realized as
an array, vector, list, or
sequence.
Your example matches the second structure - the ordered list of values.
Also from json.org:
An array is an ordered collection of
values. An array begins with [ (left
bracket) and ends with ] (right
bracket). Values are separated by ,
(comma).
A value can be a string in double
quotes, or a number, or true or false
or null, or an object or an array.
These structures can be nested.
Doesn't leave much to the imagination. You've got a valid JSON array there. Have fun with it. But just to be annoyingly thorough:
From the RFC
RFC 4627, Section 2
2) JSON Grammar
A JSON text is a sequence of
tokens. The set of tokens includes
six structural characters, strings,
numbers, and three literal names.
A JSON text is a serialized object
or array.
JSON-text = object / array
The result looks like this for me:
[[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32],[25,32]]
Which is fine as far as I can see. It might look a bit weird, but that is mostly because JSON is used a lot for objects, which have a slightly different notation. You can eval the string and get the array structure back though, so it looks fine to me.

Categories