Converting JSON to an array - javascript

I have a variable that contains the following JSON string:
{
"0" : "Jun 20, 2012 03:02 PM",
"1" : "Jun 20, 2012 03:26 PM",
"2" : "Jun 21, 2012 01:12 PM",
"3" : "Jun 21, 2012 01:25 PM",
"4" : "Jun 21, 2012 02:42 PM",
"5" : "Jun 21, 2012 02:43 PM",
"6" : "NULL"
}
I wish to convert this JSON to an array in javascript such that
array[0] has "Jun 20, 2012 03:02 PM" array[1] has "Jun 20, 2012 03:26 PM" and so on.

You must parse your JSON string into a javascript object first.
JavaScript
var object = JSON.parse(JSONString);
To polyfill browsers without JSON support:
http://bestiejs.github.com/json3/
Then, convert that object to an array:
JavaScript
var arr = [];
for(var i in object) {
if(object.hasOwnProperty(i)) {
arr.push(object[i]);
}
}
jQuery
var arr = $.map(obj,function(value){ return value; });
Fiddle: http://jsfiddle.net/iambriansreed/MD3pF/
Note: Since the original poster did not mention jQuery it is worth mentioning that loading jQuery for only these instances isn't worthwhile, and you would be better off using the pure JavaScript if you aren't already using jQuery.

Alternatively, if you're targeting ES5 and above:
// myObject = { '0': 'a', '1': 'b' };
var myArray = Object.keys(myObject).map(function(key) { return myObject[key]; });
// myArray = [ 'a', 'b' ];

var currentVersion = {/literal} {$displayedVersion} {literal};
var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');

Related

How to create individual object from a list of object?

I have a list of different objects like this:
Object: { "march 2019": 21, "april 2019": 23, "may 2019": 121, etc... }
How can I set up individual objects from this previous list in javascript or jQuery?
Object: { "march 2019": 21 }
Object: { "april 2019": 23 }
Object: { "may 2019": 121 }
Thank you for your help
You could do with Object.entries and Array#map
updated with 3 different answer
const obj = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
let res = Object.entries(obj).map((a,b)=>({[a[0]]:a[1]}));
//array object
console.log(res)
//single object
console.log(Object.assign({},...res))
//object object
console.log(res.reduce((a,b,c)=>(a[c]=b,a),{}))
You can either store the object in array or you can directly use inside the loop :
const obj = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
Object.entries(obj).forEach(ob=>console.log({[ob[0]]:ob[1]}))
Hopefully it should work
You can try the following, this will give a single object:
let input_dict = { "march 2019": 21, "april 2019": 23, "may 2019": 121};
let output_dict = {};
Object.keys(input_dict).map(function (item) {
!output_dict.hasOwnProperty(item)?output_dict[item] = input_dict[item]:'';
});
console.log(output_dict)

How to combine two javascript array into one and group by date

Hello I'am new to programming and I stumble upon on grouping array data by date from two arrays.
here is my arrays:
header = [
{"2019-04-22": "Sun, Apr 22, 2019"},
{"2019-04-21": "Sat, Apr 21, 2019"},
]
body = [
{"2019-04-22": "doing customer support”},
{"2019-04-22": "reply to emails"},
{"2019-04-21": "send message to customers"},
]
How do I group the arrays into one array as example below
combinearray = {
"2019-04-22": [
"Sun, Apr 22, 2019",
"doing customer support",
"reply to emails",
],
"2019-04-21": [
"Sat, Apr 21, 2019",
"send message to customers",
],
}
Grouping two array data by date seems completely not easy for me I'm a beginner to javascript programming. I would appreciate any answers.
You can do that in following steps:
First use concat() to combine both arrays i.e header and body
Then use reduce() on that. And pass empty object as second argument(the initial value of accumulator).
In inside reduce() callback use Object.keys()[0] to get date.
Check if the date if date is not already key of accumulator set it to empty [].
Use push() to add the elements to the array.
Note: This will not remove reference to the real object in header and body.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a)
return ac;
},{})
console.log(res)
However as mentioned in the comments there is no need to have object with keys. Just simple array of the values of that key are enough. For that push() a[key] instead of a.
const header = [ {"2019-04-22": "Sun, Apr 22, 2019"}, {"2019-04-21": "Sat, Apr 21, 2019"} ]
const body = [ {"2019-04-22": "doing customer support"}, {"2019-04-22": "reply to emails"}, {"2019-04-21": "send message to customers"}, ]
const res = header.concat(body).reduce((ac,a) => {
let key = Object.keys(a)[0];
ac[key] = ac[key] || [];
ac[key].push(a[key])
return ac;
},{})
console.log(res)
You can use combine arrays then use reduce
used spread syntax to merge arrays
use reduce to build an object in desired format
Object.entries to get date and it's respective value
Check if the date is already present as key on object or not, if it's already present push the value to it else create a new key
let header = [{"2019-04-22": "Sun, Apr 22, 2019"},{"2019-04-21": "Sat, Apr 21, 2019"},]
let body = [{"2019-04-22": "doing customer support"},{"2019-04-22": "reply to emails"},{"2019-04-21": "send message to customers"},]
let final = [...header,...body].reduce((op,inp) => {
let [key,value] = Object.entries(inp)[0]
op[key] = op[key] || []
op[key].push(value)
return op
},{})
console.log(final)

Accessing json in javascript and displaying it in html

I can't figure out why this isn't displaying in my HTML.
I've followed the following examples...
https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/
http://www.w3schools.com/js/js_json_intro.asp
How to access JSON in JavaScript
Accessing Json in Javascript
I can't seem to figure out where I'm going wrong.
This is what I've got going, currently:
window.onload = function() {
var json = { "year" : "2016",
"months" : [ {"July"}, {"August"}, {"September"} ],
"days" : [ {02}, {03}, {14}, {18}, {10}, {19} ],
"event" : [ {"Fitness assessment"}, {"Pathology-Uric Acid"}, {"Consultation-General and angiogram"}, {"Medication-Asperlone"}, {"Medication-Celestamine"}, {"Fitness assessment"} ]
};
var obj = JSON.parse(json);
document.getElementById("month").innerHTML = obj.months[0];
document.getElementById("day").innerHTML = obj.days[0];
document.getElementById("event").innerHTML = obj.event[0];
document.getElementById("day2").innerHTML = obj.days[1];
document.getElementById("event2").innerHTML = obj.event[1];
document.getElementById("month2").innerHTML = obj.months[1];
document.getElementById("day3").innerHTML = obj.days[2];
document.getElementById("event3").innerHTML = obj.event[2];
document.getElementById("day4").innerHTML = obj.days[3];
document.getElementById("event4").innerHTML = obj.event[3];
document.getElementById("day5").innerHTML = obj.days[4];
document.getElementById("event5").innerHTML = obj.event[4];
document.getElementById("month3").innerHTML = obj.months[2];
document.getElementById("day6").innerHTML = obj.days[5];
document.getElementById("event6").innerHTML = obj.event[5];
};
HTML snippet:
<div class="row liketablerow">
<div class="col-xs-2">
<h4 id="day"></h4>
</div>
<div class="col-xs-2">
<img src="images/icon-fitness.png" class="fitness" >
</div>
<div class="col-xs-2">
<p id="event"></p>
</div>
</div>
All helpful comments are helpful, thank you.
Your "JSON" isn't actually JSON. It's a JavaScript object. As such, JSON.parse won't do anything to it (except break). It's already in the format you need.
var obj = { "year" : "2016",
"months" : [ {"July"}, {"August"}, {"September"} ],
"days" : [ {02}, {03}, {14}, {18}, {10}, {19} ],
"event" : [ {"Fitness assessment"}, {"Pathology-Uric Acid"}, {"Consultation-General and angiogram"}, {"Medication-Asperlone"}, {"Medication-Celestamine"}, {"Fitness assessment"} ] };
^^ change to obj
See here for the different between JSON and a JS object literal:
What is the difference between JSON and Object Literal Notation?
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/
Your json object is not valid, you are using curly brackets for strings in your arrays which is not the correct way to do it using the json notation, here is how it should be :
var json = {
"year" : "2016",
"months": ["July", "August", "September"],
"days": [02, 03, 14, 18, 10, 19],
"event": ["Fitness assessment", "Pathology-Uric Acid", "Consultation-General and angiogram", "Medication-Asperlone", "Medication-Celestamine", "Fitness assessment" ]};
The javascript object notation seems to be wrong. Your events JS object syntax should be below instead :
var json = { "year" : "2016",
"months" : [ "July", "August", "September" ],
"days" : [ 02, 03, 14, 18, 10, 19 ],
"event" : [ "Fitness assessment", "Pathology-Uric Acid", "Consultation-General and angiogram", "Medication-Asperlone", "Medication-Celestamine", "Fitness assessment" ]
};

Object returning NaN when sum values

I'll admit I'm weak in JavaScript and JSON. I've spent a lot of time attempting to figure out why numbers from my objects returns NaN when they are added together. With that in mind, below is my JSON, stored to a variable:
var data = [
{
"acc_ext_id": null,
"cat_code": 10002,
"cat_ds": "REVENUE",
"category_id": null,
"chart_id": null,
"created_at": null,
"dept_id": null,
"feb": null,
"id": null,
"jan": 30,
"note": null,
"total_cost": null,
"updated_at": null,
"year_id": null
},
{
"acc_ext_id": "41260-02600",
"cat_code": 10002,
"cat_ds": "REVENUE",
"category_id": 2,
"chart_id": 2373,
"created_at": "2013-01-15 16:43:52.169213",
"dept_id": 86,
"feb": 45,
"id": 3,
"jan": 60,
"note": "Two",
"total_cost": 105,
"updated_at": "2013-01-15 16:43:52.169213",
"year_id": 1
}
]
I then attempt to iterate over the objects and sum the values:
var jan;
for (var i=0;i<data.length;i++){
if(data[i].jan != null){
jan += parseFloat(data[i].jan);
console.log(jan);
}
}
Printed out in the console is NaN. I've attempted to parse the number as well as leave it raw, but to no avail. Is there something wrong with my objects? Here is a jsFiddle to illustrate: http://jsfiddle.net/5E2pm/3/
var jan = 0; //this should solve it
for (var i=0;i<data.length;i++){
if(data[i].jan != null){
jan += parseFloat(data[i].jan);
console.log(jan);
}
}
Try this should solve it :)
Explanation as quoted by DON in comments below:
var jan; this will declare variable as undefined, so when you try to
add values with undefined you will get as NaN, so the answer here with
var jan = 0 will work – DON
2021
This is a good use for a reducer
const jan = data.reduce(function(total, current) {
return total + current.jan;
}, 0); // starting value
OLD ANSWER
I like this approach. It basically sets the value to 0 on the first iteration when jan doesn't exist.
jan = (jan || 0) + parseFloat(data[i].jan);
you need to initialize jan first
var jan = 0;
here's the example - link

How do I serialize this into JSON?

{
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg",
"image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg",
"date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)",
"flickr_id" : "5126544615"
}
One of the elements in thelist is above.
thejson = simplejson.dumps({"results":thelist})
However, I can't serialize this because of the date field. It can't serialize datetime.
I doubt that the problem has to do anything with datetime: in your dictionary, there is no datetime object at all, but the "date" key has a regular string value.
More likely, the problem is that it can't serialize the ObjectId class. To overcome this limitation, create a new class inheriting from JSONEncoder, and overriding the default method.
Unless i'm missing something - its the ObjectId that is causing the error (works for me here without it). You might want to consider munging or removing that field if not needed.
The date parses fine.
This works for me. I have removed ObjectId as I do not have the class with me.
result = {
"loc" : {
"lat" : 37.799506,
"long" : -122.459445
},
"test_set" : 1,
"title" : "Melissa Mills Housewife 01 SIGNED",
"num_comments" : 58,
"down_votes" : 66,
"up_votes" : 79,
"image_url" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg",
"image_url_thumb" : "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg",
"date" : "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)",
"flickr_id" : "5126544615"
}
import simplejson
thejson = simplejson.dumps(result)
print thejson
Output:
{"down_votes": 66, "loc": {"lat": 37.799506000000001, "long": -122.459445}, "image_url": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_m.jpg", "test_set": 1, "title": "Melissa Mills Housewife 01 SIGNED", "up_votes": 79, "num_comments": 58, "image_url_thumb": "http://farm2.static.flickr.com/1374/5126544615_79170591e5_t.jpg", "date": "Fri Oct 29 2010 21:55:23 GMT+0000 (UTC)", "flickr_id": "5126544615"}
And if you are getting the following error, then you need to have class ObjectId :
"_id" : ObjectId("4ccb42cb8aad692e01000004"),
NameError: name 'ObjectId' is not defined

Categories

Resources