这是一个绝妙的事情。
我有以下 .json 格式的文件:
"response": {
"tickets": [
{
"alias": "Lower Box 122",
"curr_price": 16.0,
"quantity": 2,
"seats": "17,18",
},
{
"alias": "Lower Box 122",
"curr_price": 8.0,
"quantity": 5,
"seats": "1,2,3,4,5",
},
{
"alias": "Lower Box 122",
"curr_price": 14.0,
"quantity": 7,
"seats": "6,7,8,9,10,11,12",
},
{
"alias": "Lower Box 123",
"curr_price": 16.0,
"quantity": 2,
"seats": "17,18",
},
{
"alias": "Lower Box 123",
"curr_price": 8.0,
"quantity": 5,
"seats": "1,2,3,4,5",
},
{
"alias": "Lower Box 123",
"curr_price": 14.0,
"quantity": 7,
"seats": "6,7,8,9,10,11,12",
}
]
}
我正在尝试获得此输出:
Lower Box 122,
quantity: 15,
seats: 1,2,3,4,5,6,7,8,9,10,11,12,17,18,
price: 8-16
Lower Box 123,
quantity: 15,
seats: 1,2,3,4,5,6,7,8,9,10,11,12,17,18,
price: 8-16
不幸的是,无法重新格式化原始 JSON 文件。我必须处理它目前的格式。
我不一定再次需要 .json 格式的文件。将文本吐出到页面上就可以了。谁能向我指出一个可以完成此操作的实用程序?或者一个可以解决这个问题的脚本?
难度:仅限 JavaScript。
我要感谢所有提供答案的人 - 希望这对其他人有用。
最佳答案
<script type="text/javascript">
$(document).ready(function () {
var response = {"tickets":[{"alias":"Lower Box 122","curr_price":16.0,"quantity":2,"seats":"17,18",},{"alias":"Lower Box 122","curr_price":8.0,"quantity":5,"seats":"1,2,3,4,5",},{"alias":"Lower Box 122","curr_price":14.0,"quantity":7,"seats":"6,7,8,9,10,11,12",},{"alias":"Lower Box 123","curr_price":16.0,"quantity":2,"seats":"17,18",},{"alias":"Lower Box 123","curr_price":8.0,"quantity":5,"seats":"1,2,3,4,5",},{"alias":"Lower Box 123","curr_price":14.0,"quantity":7,"seats":"6,7,8,9,10,11,12",}]};
var seats = new Array();
var alias = "";
var quantity;
var min_price = 999999;
var max_price = -1;
$.each(response.tickets, function(key, value){
if(value.alias != alias)
{
if(alias != "")
{
seats = seats.sort(function(a,b){ return parseInt(a) > parseInt(b); });
alert(alias + "\ncurr_price: " + min_price + "-" + max_price + "\nquantity: " + quantity + "\nseats: " + seats);
}
alias = value.alias;
quantity = 0;
min_price = 999999;
max_price = -1;
seats = new Array();
}
if(value.curr_price < min_price)
{
min_price = value.curr_price;
}
if(value.curr_price > max_price)
{
max_price = value.curr_price;
}
$.each(value.seats.split(","), function(key, value){
if($.inArray(value, seats) < 0)
{
seats.push(parseInt(value));
}
});
quantity += parseInt(value.quantity);
});
//Call again for last one
seats = seats.sort(function(a,b){ return parseInt(a) > parseInt(b); });
alert(alias + "\ncurr_price: " + min_price + "-" + max_price + "\nquantity: " + quantity + "\nseats: " + seats);
});
</script>
关于javascript - 试图找出如何重新格式化 JSON 响应并重新格式化数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5010974/