2011-02-16 4 views
2

이것은 doozie입니다. 나는이 출력을 얻으려고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", 
     } 
       ] 
      } 

:

나는 다음과 같은 .json 형식의 파일을 가지고하는 것은

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 만 해당.

답변이있는 모든 사람에게 감사드립니다. 희망적으로 다른 사람들에게도 유용 할 것입니다. 당신이 쉼표로 필드를 분리하고 이후

var obj = { /* your JSON goes here */ }; 

for (var i=0; i<obj.response.tickets.length; i++) { 
    document.write(obj.response.tickets[i].alias + ",<br/>"); 
    document.write("quantity: " + obj.response.tickets[i].quantity + ",<br/>"); 
    document.write("seats: " + obj.response.tickets[i].seats + ",<br/>"); 
    document.write("price: " + obj.response.tickets[i].curr_price + "<br/><br/>"); 
} 
+0

자바 스크립트. – Orbling

+0

이 파일을 브라우저로 가져 오는 방법은'$ .getJSON()'호출입니까? – Orbling

+0

예. getJSON - getScript도 사용할 수 있습니다 – jake

답변

0

조금 그 티켓 유형을 병합 할 수 있습니다. 당신이 응답을 작성하는 방법을 요청으로

(function($) { 
    $(document).ready(function() { 
     var responses = {}; 

     $.getJSON('responsefile.json', function(data) { 
      $.each(data.response.tickets, function(index, cTicket) { 
       var cSeats = cTicket.seats.split(/,/); 

       if (responses[cTicket.alias] == undefined) { 
        responses[cTicket.alias] = { alias: cTicket.alias, 
               price: { min: cTicket.curr_price, max: cTicket.curr_price }, 
               quantity: cTicket.quantity, 
               seats: cSeats }; 
       } else { 
        var cResponse = responses[cTicket.alias]; 

        $.each(cSeats, function(i, cSeatNumber) { 
         if ($.inArray(cSeatNumber, cResponse.seats) == -1) { 
          $.merge(cResponse.seats, [cSeatNumber]); 
         } 
        }); 

        cResponse.seats.sort(function(a, b) { 
         return parseInt(a) - parseInt(b); 
        }); 

        cResponse.quantity = responses[cTicket.alias].seats.length; 
        cResponse.price.min = (cTicket.curr_price < cResponse.price.min ? cTicket.curr_price : cResponse.price.min); 
        cResponse.price.max = (cTicket.curr_price > cResponse.price.max ? cTicket.curr_price : cResponse.price.max); 

        responses[cTicket.alias] = cResponse; 
       } 
      }); 

      var responseSet = []; 
      $.each(responses, function(index, cResponse) { 
       responseSet.push(cResponse); 
      }); 
      responseSet.sort(function(rA, rB) { 
       return (rA.alias < rB.alias ? -1 : (rA.alias > rB.alias ? 1 : 0)); 
      }); 

      processResponses(responseSet); 
     }); 

    }); 
})(jQuery); 

, 나는 약간 출구에서 수행하는 함수를 호출하는 코드로 변경했다. 이 함수를 올바른 위치를 가리 키도록 다음과 같이 조정하십시오.

(function($) { 
    function processResponses(responses) { 
     var responseText = ''; 
     var csv = "alias,quantity,seats,price\n"; 

     $.each(responses, function(index, cResponse) { 
      responseText = responseText 
          + cResponse.alias + ",\n" 
          + "quantity: " + cResponse.quantity + ",\n" 
          + "seats: " + cResponse.seats.join(',') + ",\n" 
          + "price: " + cResponse.price.min + (cResponse.price.min == cResponse.price.max ? '' : '-' + cResponse.price.max) + "\n"; 
      csv = csv 
        + cResponse.alias + "," 
        + cResponse.quantity + "," 
        + cResponse.seats.join(' ') + "," 
        + cResponse.price.min + (cResponse.price.min == cResponse.price.max ? '' : '-' + cResponse.price.max) + "\n"; 
     }); 

     $('#text-output-location').text(responseText); 
     $('#csv-output-location').text(csv); 
    } 
})(jQuery); 

주들이 탈출을 많이 필요로하고 선명도를 줄일 분리 쉼표로 CSV 출력의 공간 별도의 좌석 값이 필요.

데모 : http://jsfiddle.net/p5QUb/

NB. 데모 버전에는 특수 처리가 필요한 jsfiddle.net에서 AJAX를 수행 할 수 있도록 약간의 수정이 있었으며 줄 바꿈을 추가하기 위해 출력을 약간 변경했습니다.

+0

이것은 좋은 일이지만 div 나 목록 항목 등을 작성하는 방법을 알아 내지 못했습니다 ... – jake

+0

@jake : 나는 당신을 위해 그것을하기 위해 일상적으로 대답을 확장했습니다. – Orbling

+0

얼버무 리기 - 이것은 대단합니다! 맥주도 당신을 위해! 그러나 이것은'respond.sort (function (rA, rB) { return (rA.alias rB.alias? 1 : 0)); }); '오류가 계속 발생합니다. 내가 그 기능을 제거하면, 그것은 작동하기 시작 .. 어떤 생각? 그것을 위해 인터넷 검색 아무것도 위로하지 않았다. – jake

0

다음은 당신을 위해 올바른 형식으로 뱉어 귀하의 가치 중 쉼표가있는 경우 거기에 모호함이 있습니다. 당신의 JSON 가정

data라는 개체로 해석됩니다, 당신은 단지 jQuery를 사용할 수 있습니다 위해 필요한 작업

jQuery.map(data.response.tickets, function(elt) { 
    var fields = []; 
    fields.push(elt.alias); 
    fields.push("quantity:" + String(elt.quantity)); 
    fields.push("price:" + String(elt.curr_price)); 
    fields.push("seats:" + elt.seats); 
    return fields.join(",\r\n"); 
}).join("\r\n\r\n"); 
+0

좌석을 병합하거나 가격 범위를 만들지 않습니다. – Orbling

+0

아주 좋은 지적입니다! 그게 내 질문을 제대로 읽지 못하게 해줄거야. – Jon

0

내가, 당신이 비록 그 샘플 출력을 구문 분석하는 것입니다 방법을 잘 모르겠지만, 하나

2
<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> 
+0

최소 및 최대 가격이 동일한지 여부를 감지하는 코드를 추가하여 예를 들어 1 개 또는 다른 하나만 표시 할 수도 있습니다. 16-16 – Rob

+0

빙고! 너 한테 맥주 사 줄까? – jake

+0

@jake - mmm beer :-) 대답을 올바르게 표시하는 것을 기억할 필요가 없습니다 .-) – Rob

1

Underscore.js을 포함 시키려면 reduce/lfold 메서드를 사용할 수 있습니다. 나는 그것에게 탄을 준,하지만 난 조금을 neatened 수 의심 : 당신을 잎

_.reduce(x.response.tickets, function(memo, obj){ 
    memo[obj.alias] = memo[obj.alias] || {quantity:0, seats:[]}; 
    memo[obj.alias].maxPrice = 
     Math.max(memo[obj.alias].maxPrice || obj.curr_price, obj.curr_price); 
    memo[obj.alias].minPrice = 
     Math.min(memo[obj.alias].minPrice || obj.curr_price, obj.curr_price); 
    memo[obj.alias].quantity += obj.quantity; 
    memo[obj.alias].seats = 
     memo[obj.alias].seats.concat(_.map(obj.seats.split(","), function(v){ 
      return parseInt(v,10); 
     })); 
    memo[obj.alias].seats.sort(function(a,b){return a-b;}); 
    return memo; 
}, {}) 

을 :

{ 
    "Lower Box 122": { 
     "quantity": 14, 
     "seats": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 18], 
     "maxPrice": 16, 
     "minPrice": 8 
    }, 
    "Lower Box 123": { 
     "quantity": 14, 
     "seats": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 17, 18], 
     "maxPrice": 16, 
     "minPrice": 8 
    } 
} 

또한 배열로 결과를 않으려면 객체가 아니라 해시, 당신이 이런 식으로 변환 할 수 있습니다 (var k을 가정하고 위의 배의 결과입니다) : 아마도 jQuery를, 당신이 태그로 jQuery로

_.keys(k).map(function(alias){ 
    k[alias].alias = alias; 
    return k[alias]; 
}) 
+0

jsfiddle : http://jsfiddle.net/ctrlfrk/28axx/1/ – david

+0

이것은 꽤 멋지다! 나는 이것에 대해 주위를 어지럽 혔지 만 getJSON 호출에서 결과를 검색하고 변수에 json을 저장 한 다음 _underscore 스크립트에서 변수에 액세스하는 방법을 확신 할 수 없습니다. 올바른 방향으로 나를 가리킬 수 있습니까? – jake

+0

@david : jQuery는 폴드 중 하나가 누락되어 있으며, 여기에 대한 확장 기능을 어느 시점에서 작성했으며, 검색이 싫어지면 이제는 찾을 수 없습니다. 아직 밑줄을 사용하지 마십시오. – Orbling

관련 문제