-1

一部の Json データを特定の形式に変換しようとすると、いくつかの問題が発生します。

私は基本的にこのJsonデータが必要です:

{
query: [ ],
products: 
[

{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link1.php"
},


{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link2.php"
},


{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link3.php"
}
]

この JavaScript 配列に入るには:

var arrProducts = [
                          title:  "{{ product.title }}",
                          url:  "{{ product.url }}",
                          label:  "{{ product.title }}",
                          magazine: "{{ product.magazine }}",
                          image: "{{ product.imageThumb }}",
                          newsstand: "{{ product.newsstand }}",
                          kindle: "{{ product.kindle }}",
                          barnesnoble: "{{ product.barnesnoble }}",
                          zinio: "{{ product.zinio }}",
                          kobo: "{{ product.kobo }}",
                          waterstones: "{{ product.waterstones }}",
                          type: "{{ product.type }}",
                      },
             ];

私は使用してみました:

var allProducts = $.get("http://localhost:8888/web/app_dev.php/api/v1/search/search.json, function(data) {

var productsArray = data.products; 

console.log(productsArray);

});

しかし、その方法では、必要な形式で配列が構築されません。Console.log は一連のオブジェクトを出力します。たぶん、for each ループが解決策になるでしょうか? -どんな助けでも大歓迎です、私のJavascriptはそれほど素晴らしいものではありません!

4

1 に答える 1

1

use http://jsonlint.com to validate your json. If it won't pass there, it won't pass through ajax either. Your sample is missing double quotes on object keys and a starting brace and has extra comma and your file shoudn't include var arrProducts = when consumed by ajax

There is a difference however if you place a script tag with this file in page during initial page load. Then the var arrProducts = is needed and the quotes on object keys are not. Then rather than ajax you would simply loop over the variable arrProducts

EDit:

To loop over first sample

$.getJSON( url, function(data) { 
    var productsArray = data.products;  
    $.each(  productsArray, function( i, item){ 

         console.log( 'Title is '+ item.title)

    })

})

There is a wealth of information available about how to parse json and loop over objects and arrays ... did you try searching?

于 2012-10-29T13:22:17.673 に答える