Adding an Individual JSON Object to an Array to Parse and Process - javascript

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.

Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array

This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...

Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

Related

Loading string format arrays into an array

I am getting a set of Arrays in string format from Database like
["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]
Now I need to load them into array to make an array of arrays. Using this code
let imgIndicators = [];
imgIndicators.push( obj[i]['dicatorsbg']);
console.log(imgIndicators);
is creating an array like
["["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]"]
which as you can see is big long string item, so I tried splitting the data by , like
imgIndicators.push( obj[i]['dicatorsbg'].split(','));
This time code is accepting all , and creating an array of 6 string elemet like
["["#464b4e"", ""#7ebcbd"]", " ["#747493"", ""#f5f6f7"]", " ["#58383c"", ""#8d8566"]"]
How can I fix this code to create something like this?
[
["#464b4e", "#7ebcbd"],
["#747493", "#f5f6f7"],
["#58383c", "#8d8566"]
]
If you are really sure that the format will be correct, you can try:
imgIndicators = JSON.parse("[" + obj[i]['dicatorsbg'] + "]");
Its easy , You have to use JSON.parse() as shown below, shall give you your required result.
//your db output string
var yourStringArray = '["#464b4e","#7ebcbd"], ["#747493","#f5f6f7"], ["#58383c","#8d8566"]' ;
// the array you want
var requiredArray = JSON.parse("[" + yourStringArray + "]");
More solutions can be found on this thread issue : Elegant way to convert string of Array of Arrays into a Javascript array of arrays

Append string before printing JSON data

I am getting JSON data from AJAX call. So, the JSON data has format like -
data[0].scores.sadness
So, the last part 'sadness' is one of the emotions. I have total 8 emotions. So, I don't want to print like -
data[0].scores.sadness, data[0].scores.anger
So, I have created one array with all 8 emotions -
var emotions = ['anger', 'contempt', 'disgust', 'fear', 'happiness', 'neutral', 'sadness', 'surprise'];
I am using Jquery to dynamically create few elements, in 'each' loop of jQuery I'm appending array to JSON response like this -
var emotionPer = $('<div>')
.text(data[0].scores + "." + emotions[i])
.appendTo(li);
The problem I'm facing is that, it is printing [object] [object].{name of emotion}
for example -
[object] [object].anger or [object] [object].sadness
Is there any way to interpret it like -
data[0].scores.anger
So , that I can get value of above.
.text(data[0].scores[emotions[i]])
You can access the value of a key inside an object by two ways:
obj.key
obj["key"]
Why your method didn't work:
var obj = {"name":"void", "on":"stackoverflow"};
var key = "on";
obj.on // stackoverflow
obj["on"] // stackoverflow
obj.key // Will be undefined
obj[key] // will be stackoverflow.
I hope it makes sense.

convert java map to javascript map and loop over to get keys/values?

In java i have hashmap
Map<String , List<Employee>> employeeMap = new HashMap<String , List<Employee>> ();
employeeMap.put(1, new Employee());
........
I am adding it in request attribute
Now in javascript i need to loop over over map, to get keys and values
Here what i tried
Approach 1 :-
var empMap = '${employeeMap}';
//here is the example value of map in javascript which i see while debugging
//var empMap = {emp1_100=[com.Employee#5b7b4bc5], emp2...
for (var key in empMap) {
alert(key + ': ' + empMap[key]);
}
But getting syntax error
SyntaxError: missing : after property id
Approach 2 :- with jquery
var jsonMap = $.stringify(empMap);
$.each( jsonMap, function( key, value ) {
alert( key + ": " + value );
});
But its not working either. It print some characters.
I am not sure what i am missing here ?
Looks like you are simply writing whatever the .toString() method of your Map returns to the request, which is not a good idea in the first place.
If I were you, I would convert your Map into a JSON object (there various ways to do that, depending on your system) and then append the String representation of this JSON object to the request, because then you can simply call "JSON.parse( ... );" in JavaScript to transform it into a JavaScript object without having to do any parsing yourself.

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

Deserializing the result of jQuery.Serialize (to an array - not to a form)

Is it possible to deserialize the result of jQuery.Serialize to an array (or other similar JavaScript data structure)?
I know about the jQuery.Deserialize plugin but I don't think you can get the deserialized data; i.e., it is for deserializing back to the original form (from which you previously serialized the data).
If You want it as an array , try using serializeArray instead of serialize, that gives you the elements mapped to their names as an associative array.
.serializeArray()
As #SpiXel has shown you can use serializeArray to generate an array from a <form> element.
There is no function available in jQuery to convert the string generated by serialize function. You have to do something as shown below
var paramString = $("#cform").serialize();
var jsonString = '{"' + paramString.replace(/[&=]/g, function(a, b) {
return (a == "&" ? ",\"" : "\":");
}) + '}';
var object = $.parseJSON(jsonString);
Try using this syntax, Hope It will help you.
var d = $('#form4').serializeArray();
d.push({lead_id : $("#lead_id").val()});

Categories

Resources