0

I've generated the following JSON Object in php and am passing it through AJAX to my javascript. This JSON object as is will not suffice since the Google Charts API I am using needs a javascript date object for each date in the JSON.

My dates are currently encoded in UNIX timestamp -- 1199170800,1201849200,1343800800,1346479200. I figure I could add a regex quantifier on one side of the timestamp (ie: ~1346479200), use REGEX to find the date based on the quantifier, convert the date to javascript object, and then replace each quantifier with the regex. Easier said then done for some.

{"cols":[{"type":"date","label":"FromDate"},{"type":"number","label":"Electricity Use     
(KWH)"},{"type":"number","label":"Cooling Degree Days"}],"rows":[{"c":       
[{"v":1199170800,"f":"Jan-08"},{"v":"559280","f":"559,280"},{"v":"0"}]},{"c":
[{"v":1201849200,"f":"Feb-08"},{"v":"653193","f":"653,193"},{"v":"381"}]},{"c":
[{"v":1343800800,"f":"Aug-12"},{"v":"667874","f":"667,874"},{"v":"322"}]},{"c":
[{"v":1346479200,"f":"Sep-12"},{"v":"687299","f":"687,299"},{"v":"101"}]}]} 

I've looked through many similar posts to get some ideas, but I can't solve this one... Similar, seemingly useful posts:

Loop through object get value using regex key matches Javascript

http://sudarshanbhalerao.wordpress.com/2011/08/14/convert-json-date-into-javascript-date/

Date Range Google Chart Tools

Community
  • 1
  • 1
user1824797
  • 89
  • 2
  • 11

1 Answers1

0

No regular expressions needed.

  • Parse the JSON into a JavaScript object.
  • Loop through the "rows" key of the resulting object.
  • For each item, get the "c" key, which looks like it's the value you need.
  • In the above example, the values are strings, so you should convert them to integers using parseInt.
  • Create a new Date object with each one, and pass it the integer value, multiplied by 1000. If you do new Date(integer), it will create an object using that timestamp, but the value is expected to be in milliseconds, not seconds like a normal UNIX timestamp.
Community
  • 1
  • 1
JW.
  • 50,691
  • 36
  • 115
  • 143