Link to home
Start Free TrialLog in
Avatar of Jayesh Acharya
Jayesh AcharyaFlag for United States of America

asked on

help using javascript to pull out data from a json file

I have a json row that i am trying to process example below
{"CustomerNum":"12345","Activity_Date":"1/24/16"}

so assume this data is passed to my function, I need to pull out the customer number and split the activity date into three other attributes.


function (context, myDataQueRow) {    
..
..
   // get a copy of the data
    var ActvityData = myDataQue;
       
    //looking to place the values of this data into other variables
      var CustNum =  // get the value from Customer Number
      
      // the date is pulled from Activity_date, and has a format of MM / DD / YY
      var ActivityMonth  = // Activity_date pull from the 1st char up to the 1st /
      var ActivityDay  = // Activity_date pull from the 1st / up to the second /
      var ActivityYear = // Activity_date pull from the second / up to the end, also prefix with 20 since need 4 digit year
..
..
..
SOLUTION
Avatar of Leonidas Dosas
Leonidas Dosas
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Leonidas:  It's better to use a Date object than parse the string.
Avatar of Jayesh Acharya

ASKER

on the line
var d = new Date(json.Activity_Date);

// is there a way to specify the format of the date, in this case its MM/DD/YY, but in other cases I have DD/MON/YYYY e.g. 24/JAN/2016

also trying to understand this line
console.log(d.getMonth() + 1);

// what is the + 1 needed for?  if I would of read that in other languages I would of thought that would give me a value for February in this case
Regarding the format of the date:  If possible, it would be best to standardize your date format before passing in json, so that all of the Activity_Date results are in the same format.

If that is not possible, you will need to pass some kind of flag or indicator so that you know what format Activity_Date is in, and then parse the Activity_Date string accordingly to create a JS date object.  This is not the ideal method.

Regarding getMonth() + 1:
An integer number, between 0 and 11, representing the month in the given date according to local time. 0 corresponds to January, 1 to February, and so on

getMonth() is indexed starting at 0, so if you want to correlate the result with the months of the year, you need to add one.  Otherwise, you'll need to account for 0 being January.
Thank you both for the information, this is a bit of life saver for me trying to understand how this actually works.