[{"code":10,"shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":0}]
变化
(int to string)=> particular value "code"=10-> "code"="10" , "isselect":0->"isselect":"0"
我希望输出
[{"code":"10","shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":"0"}]
答案 0 :(得分:1)
尝试以下方法:
var data = [{"code":10,"shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":0}];
data[0].code = String(data[0].code);
如果要将所有属性更改为字符串,则在数组的所有元素中,
function change_properties_to_strings(arr) {
return arr.forEach(function(obj) {
Object.keys(obj).forEach(function(key) {
obj[key] = String(obj[key]);
});
});
}
换句话说,遍历数组的元素,每个元素都是一个对象。对于每个对象,循环其键(属性名称)。对于每个键,将该属性的值更改为字符串。
如果您更喜欢for-loops,可以使用相同的逻辑编写:
function change_properties_to_strings(arr) {
for (var i = 0; i < arr.length; i++) {
var obj = arr[i];
for (var k in obj) {
obj[k] = String(obj[k]);
}
}
}
答案 1 :(得分:0)
在Java中:
我会删除所有打开和关闭括号/括号,然后按",|:"
拆分。迭代数组,从分割中,如果它们不存在则在值周围添加引号,同时将它们添加回新构造的json String
。
示例:
public static void main(String[] args) throws Exception {
String json = "[{\"code\":10,\"shtdesc\":\"CoOrdHR\",\"name\":\"CO-ORDINATOR - HR\",\"isselect\":0}]";
// Split out each value
String[] jsonPieces = json.replaceAll("[\\[\\]{}]", "").split(",|:");
// Reconstruct json
StringBuilder sb = new StringBuilder("[{");
for (int i = 0; i < jsonPieces.length; i++) {
// Add quotes if they're not there
if (!jsonPieces[i].startsWith("\"")) {
jsonPieces[i] = "\"" + jsonPieces[i] + "\"";
}
// Append json piece
sb.append(jsonPieces[i]);
// Append ":" or ","
if (i + 1 < jsonPieces.length) {
sb.append(i % 2 == 0 ? ":" : ",");
}
}
// Append closing
sb.append("}]");
// Reassign back to json
json = sb.toString();
// Display results
System.out.println(json);
}
结果:
[{"code":"10","shtdesc":"CoOrdHR","name":"CO-ORDINATOR - HR","isselect":"0"}]
答案 2 :(得分:0)
试试这个例子
var arr = [{
"code": 10,
"shtdesc": "CoOrdHR",
"name": "CO-ORDINATOR - HR",
"isselect": 0
}];
alert(JSON.stringify(arr));
var transform = function(list) {
var l = list.length;
var o;
while (l--) { //loop through each json
o = list[l];
for (var k in o) // loop through each key in json
if ('number' === (typeof o[k])) // only if property value is number
o[k] = o[k].toString();
}
return list;
};
alert(JSON.stringify(transform(arr)));
&#13;