JSON:
{
"time":"1520480018644",
"start":"0",
"search":{
"search":"",
"smart":"true",
"regex":"false",
"caseInsensitive":"true"
},
"columns":[
{
"visible":"false",
"search":{
"search":"",
"smart":"true",
"regex":"false",
"caseInsensitive":"true"
},
"width":"200px"
},
{
"visible":"true",
"search":{
"search":"",
"smart":"true",
"regex":"false",
"caseInsensitive":"true"
},
"width":"200px"
}
]
}
程序:
$.each(json_data, function(index, val) {
$.each(val, function(index1, val1) {
if(val1 == 'true'){
json_data[index][index1] = True;
}
if(val1 == 'false'){
json_data[index][index1] = False;
}
});
});
正如您可以在字符串中看到所有布尔值。如何将字符串分别更改为boolean?我没有任何替代方法,我只需要将字符串分别更改为boolean。抱歉我的英语不好。
答案 0 :(得分:0)
创建一个简单的toBoolean
方法
function toBoolean( str )
{
return str == "true";
}
并将其用作
$.each(json_data, function(index, val) {
$.each(val, function(index1, val1) {
json_data[index][index1] = toBoolean( val1 );
});
});
答案 1 :(得分:0)
制作一个应该通过树的版本并更改所有嵌套的版本。
var json_data = {
"time": "1520480018644",
"start": "0",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"columns": [{
"visible": "false",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"width": "200px"
},
{
"visible": "true",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"width": "200px"
}
]
};
function processObject(object) {
//loop over the object key values or the array elements
$.each(object, function(key, value) {
//if the value is a string, we want to possibly convert it
if (typeof value === 'string') {
//only convert if the value is true/false
if (['true', 'false'].indexOf(value.toLowerCase()) > -1) {
object[key] = (value.toLowerCase() == 'true');
}
} else {
//the value is not a string, try to process it as an object or array
processObject(value);
}
});
}
processObject(json_data);
console.log(json_data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 2 :(得分:0)
试试这个有用的演示:
var jsonObj = {
"time": "1520480018644",
"start": "0",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"columns": [{
"visible": "false",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"width": "200px"
},
{
"visible": "true",
"search": {
"search": "",
"smart": "true",
"regex": "false",
"caseInsensitive": "true"
},
"width": "200px"
}
]
};
function convertBool(obj) {
if (typeof obj !== 'object') {
return;
}
for (var i in Object.keys(obj)) {
(obj[Object.keys(obj)[i]] == "true") ? obj[Object.keys(obj)[i]] = true : convertBool(obj[Object.keys(obj)[i]]);
(obj[Object.keys(obj)[i]] == "false") ? obj[Object.keys(obj)[i]] = false : convertBool(obj[Object.keys(obj)[i]]);
}
return jsonObj;
}
var convertedObj = convertBool(jsonObj);
console.log(convertedObj);
&#13;