在 jquery 客户端中格式化服务器端的 Json 字符串



这是小提琴

http://jsfiddle.net/zzk3rgrm/3/

我从下面这样的服务器获取 json 字符串

.JS

var myjsonstring = [{"Key":"item1","Value":"problem statement 1"},{"Key":"item1","Value":"problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement"},{"Key":"item2","Value":"problem statement 1"},{"Key":"item3","Value":"problem statement 1"}];
myjsonstring = JSON.stringify(myjsonstring);

alert(myjsonstring);
现在,正如您在代码中看到的那样KeyValue这些词即将出现,则应将其删除。 ","作为分隔符,所以应该删除并代替逗号,应该有一个新行,以便每个项目都显示在单独的行中。

还删除了所有 {} [] 这些字符.

因此,在警报中如下所示

item1 - problem statement 1
item1- problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement
item2- problem statement 1
item3 -problem statement 1

请在这里帮忙

myjsonstring是一个数组,可以按原样使用,而无需使用stringify

var myjsonstring = [{"Key":"item1","Value":"problem statement 1"},{"Key":"item1","Value":"problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement"},{"Key":"item2","Value":"problem statement 1"},{"Key":"item3","Value":"problem statement 1"}];

var newJson = "";
myjsonstring.forEach(function(ob){
newJson += ob.Key + ' - ' + ob.Value + 'n';
});

alert(newJson);

你可以用这个替换你的代码

var result = '';
myjsonstring.forEach(function(obj) {
result = result + obj.Key + " - " + obj.Value + "n";
});    

最新更新