我需要帮助将JSON转换为用户可读的文本。
示例JSON:
{
"condition": "or",
"rules": [{
"field": "X",
"operator": "IN",
"value": ["A", "B"]
},
{
"field": "Y",
"operator": "IN",
"value": ["C", "D"]
},
{
"condition": "and",
"rules": [{
"field": "X",
"operator": "IN",
"value": ["F", "G"]
},
{
"condition": "and",
"rules": [{
"field": "Z",
"operator": "IN",
"value": ["R", "S"]
}]
}
]
},
{
"field": "I",
"operator": "IN",
"value": ["D", "K"]
}
]
}
预期产出:
X in('A','B') OR Y in('C','D') OR ( X in('F','G') and ( Z in('R','S') ) ) OR I in('D','K')
提前感谢您的帮助。
答案 0 :(得分:0)
好吧,它看起来像一个有趣的挑战,所以我做了它,然后不小心按下了提交按钮,所以在这里。我将把它留给OP来研究它是如何工作的。
const data = { "condition": "or", "rules": [{ "field": "X", "operator": "IN", "value": ["A", "B"] }, { "field": "Y", "operator": "IN", "value": ["C", "D"] }, { "condition": "and", "rules": [{ "field": "X", "operator": "IN", "value": ["F", "G"] }, { "condition": "and", "rules": [{ "field": "Z", "operator": "IN", "value": ["R", "S"] }] } ] }, { "field": "I", "operator": "IN", "value": ["D", "K"] } ] };
const expect = "X in('A','B') OR Y in('C','D') OR ( X in('F','G') and ( Z in('R','S') ) ) OR I in('D','K')";
const utils = {
quote(s) { return `'${s}'` },
parse(obj) {
return parsers[obj.condition || obj.operator](obj);
}
};
const parsers = {
or(obj) {
return obj.rules.map(utils.parse).join(" OR ");
},
and(obj) {
return `( ${obj.rules.map(utils.parse).join(" and ")} )`;
},
IN(obj) {
return `${obj.field} in(${obj.value.map(utils.quote).join(",")})`;
}
};
const result = utils.parse(data);
console.log(`match? ${result == expect}`);
console.log(result);

答案 1 :(得分:0)
getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(this.getObjects(obj[i], key, val));
} else
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == '') {
if (objects.lastIndexOf(obj) == -1) {
objects.push(obj);
}
}
}
return objects;
}
I was able to break JSON into separate objects but stuck on combining those objects with the conditional operator and also to preserve the hierarchy. Thank you doodle for your answer.