JSON响应与颜色数据的部分键不正确匹配 [英] JSON response incorrectly matches partial key for color data

查看:112
本文介绍了JSON响应与颜色数据的部分键不正确匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于jsonData.search(key)!== -1,下面的JavaScript代码与"COMPLETED"匹配,这是错误的,因为JSON响应不包含COMPLETED,因此输出中应显示红色而不是绿色.

参考:

获取特定颜色使用JSON数据获取特定值

输出:[绿色",红色"]


预期:[红色"]

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]);
    }
});

实际输出:

由于搜索(键),颜色键首先匹配"COMPLETED-green".

预期输出:

颜色键应首先匹配"NOT_COMPLETED-红色".

如何与NOT_COMPLETED-读取颜色而不是COMPLETED-绿色相匹配?

解决方案

https://jsfiddle.net/xq7hLo6h/6/通过简单地在JSON字符串中搜索"KEY"(带引号)而不是KEY来解决此问题:

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

这样可以避免在"NOT_COMPLETED"内部发现COMPLETED的问题.

但是,更健壮的方法是实际解析JSON字符串以获取对象,然后检查实际属性.

Below JavaScript 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

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.

How can I match with NOT_COMPLETED - read color instead of COMPLETED - green color?

解决方案

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.

这篇关于JSON响应与颜色数据的部分键不正确匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆