Jits Jits - 4 months ago 11
JSON Question

JSON response incorrectly matches partial key for color data

Below java script code matches to "COMPLETED" due to jsonData.search(key) !== -1 which is wrong because json response doesn't contain COMPLETED, it should show red color instead of green in the output.

Reference:



Getting specific color for specific value using JSON data

Fiddle:



https://jsfiddle.net/jiteshsojitra/xq7hLo6h/3/


Output: ["green", "red"]




Expected: ["red"]


jsonData:



{"cols":[{"label":"sprint_status","type":"string"},{"label":"count","type":"string"}],"rows":[{"c":[{"v":"NOT_COMPLETED"},{"v":4}]}]}


JavaScript:



const colorMap = {
COMPLETED: 'green',
NOT_COMPLETED: 'red'
};

Object.keys(colorMap).forEach((key, index) => {
if (jsonData.search(key) !== -1) {
customColors.push(colorMap[key]);
}
});


Actual output:




Color key matches to "COMPLETED - green" first due to search(key).


Expected output:




Color key should match to "NOT_COMPLETED - red" first.


Can someone please help me to match with NOT_COMPLETED - read color instead of COMPLETED - green color? Thanks in advance!

Answer

This https://jsfiddle.net/xq7hLo6h/6/ fixes the issue by simply searching the JSON string for "KEY" (with quotes) instead of KEY:

if (jsonData.search("\"" + key + "\"") >= 0) { /* ... */ }

This way the problem with COMPLETED being found inside "NOT_COMPLETED" is circumvented.

However a more robust way would be to actually parse the JSON string in order to get the object and then check the actual property.