-3

How can I create a javascript function to pull data from JSON based on words? I am using an Task Manager API and want to populate fields based on the title of the task. For Example:

{
 "data": {
    "boards": [
      {
        "owner": {
          "id": 555555555
        },
        "groups": [
          {
            "id": "new_group",
            "title": "Forecasts",
            "items": [
              {
                "id": "355670938",
                "name": "PIPE: Production & Client Management | STAGE: New Support Intake | NAME: TESTY | DATE: 10/27/2019 | TIME: 8:00 am | TIME ZONE: Central Time | DURATION: 60 minutes | TYPE: All Virtual | AUDIENCE VIEW:"
              }
            ]
          }
        ]
      }
    ]
  },
  "account_id": 55555555
}

I need the information extracted from items.name for DATE, TIME, DURATION, and TYPE. How could i set up a function to pull just this information?

klaurtar
  • 233
  • 3
  • 23
  • Possible duplicate of [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – computercarguy Oct 22 '19 at 16:31

3 Answers3

1

You first need to locate where you want to extract the info from.

Then you just split on pipes, and then on colons.

let targetStr = getTree().data.boards[0].groups[0].items[0].name;
let fields = ['DATE', 'TIME', 'DURATION', 'TYPE'];

console.log(extractData(targetStr, fields));

function extractData(str, fields) {
  return str.split(/\s*\|\s*/).reduce((res, entry) => {
    let dat = entry.split(/\s*:\s*/);
    return fields.indexOf(dat[0]) > -1 ? Object.assign(res, { [dat[0]]: dat[1] }) : res;
  }, {});
}

function getTree() {
  return {
    "data": {
      "boards": [{
        "owner": {
          "id": 555555555
        },
        "groups": [{
          "id": "new_group",
          "title": "Forecasts",
          "items": [{
            "id": "355670938",
            "name": "PIPE: Production & Client Management | STAGE: New Support Intake | NAME: TESTY | DATE: 10/27/2019 | TIME: 8:00 am | TIME ZONE: Central Time | DURATION: 60 minutes | TYPE: All Virtual | AUDIENCE VIEW:"
          }]
        }]
      }]
    },
    "account_id": 55555555
  };
}
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

Assuming | isn't used ever in the data, you could do:

items.name.split('|').filter(data => /^(DATE:|TIME:|DURATION:|TYPE:)/.test(data));
Anthony
  • 6,422
  • 2
  • 17
  • 34
0

JSON.parse() takes a JSON string and transforms it into a JavaScript object. From there you can just return the value of the desired key.

Buddy
  • 10,874
  • 5
  • 41
  • 58
Sudeep Shrestha
  • 128
  • 2
  • 14