2011-11-03 81 views
0

我想問你一個關於JSON的問題。json產品數據存儲創建

我想區分產品的類別。我怎樣才能用JSON編寫?

{"products": 
{"category" : "computer"[ 
    {"brand" : "sony" 
    "price" : "$1000"}, 
    {"brand" : "acer" 
    "price" : "$400"},]} 
, 

    {"category" : "cell phone"[ 
     {"brand" : "iphone" 
     "price" : "$800"}, 
     {"brand" : "htc" 
     "price" : "$500"},]} 
} 

回答

1

我想你可能需要的東西是這樣的:

{"products": 
    {"computer": 
    [ 
     {"brand" : "sony", 
     "price" : "$1000"}, 
     {"brand" : "acer", 
     "price" : "$400"} 
    ], 
    "cell phone": 
    [ 
     {"brand" : "iphone", 
     "price" : "$800"}, 
     {"brand" : "htc", 
     "price" : "$500"} 
    ] 
    } 
} 

使用類別作爲JSON對象的鍵,你可以很容易地訪問所有的產品在該類別中,例如:

>>> data['products']['computer'] 
[{'brand': 'sony', 'price': '$1000'}, {'brand': 'acer', 'price': '$400'}] 

如果需要,還可以向頂層JSON對象添加類別列表,以便知道可用的類別:

{"products": {...}, 
"categories": ["computer", "cell phone"] 
} 
+0

非常感謝它的作品! –