json产品数据存储创建

时间:2011-11-03 21:20:36

标签: 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 个答案:

答案 0 :(得分: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"]
}