Help with JS: How do I parse?

{“component”:{“key”:“repo1”,“name”:“repo1”,“description”:“TEST.”,“qualifier”:“TRK”,“measures”:[{“metric”:“complexity”,“value”:“12345”},{“metric”:“ncloc”,“value”:“6789”},{“metric”:“violations”,“value”:“147”,“bestValue”:false}]}}
I’m getting this JSON response (with modified values due to privacy) from SonarQube. When importing to EazyBI from RestAPI I’d like to make each ‘metric’ a column. The question is: how do I parse when the responses are not static? The JSON responses are not fixed - each return will have them ordered diferently so using the JS Path $.measures[#] (where # = the property(I think it’s a property)).
What I’ve tried:

const json = doc.component.measures;
const obj = JSON.parse(json);
return obj.measures[*].complexity

This doesn’t even execute. I get a token error “SyntaxError: Unexpected token: o”
This is a screenshot of the data in Firefox:
image

Hi @MichaelW,

Given the JSON structure returned by the REST API, I would recommend using the path $.component. That way, you would also have a key and name value to use as a dimension.

The “measure” values are in an array that you can iterate through and check the metric name. The custom JavaScrpt code could look similar to the one below:

let complexity;
let ncloc;
let violations;
if (doc.measures && doc.measures.length > 0) {
  for (i = 0; i < doc.measures.length; i++) {
    switch (doc.measures[i].metric) {
      case 'complexity':
        complexity = doc.measures[i].value;
        break;
      case 'ncloc':
        ncloc = doc.measures[i].value;
        break;
      case 'violations':
        violations = doc.measures[i].value;
        break
    }
  }
}
doc.complexity = complexity;
doc.ncloc = ncloc;
doc.violations = violations;

After that you should have three new columns in the data mapping screen. See more details on altering data with custom JavaScript code here - Import from REST API.

Best,
Roberts // support@eazybi.com

It only took me three months to get to this - my apologies! Your JS code worked beautifully. I really appreciate the help.

1 Like