我想知道构建json字符串的最佳方法是什么?
我有一种产品可能有不同的变化,每种变化可能会有不同的价格增加或没有:
color: black, +$5
color: white, +$0
size: L, +$1
size: XL, +$4
big bada boom: No, $-4
and so fourth
你会建议假设任何给定的属性(颜色,大小等)没有在任何地方定义并且需要动态解析?
你觉得这样的事情有意义吗?
{
"variations": {
"Color": [
{
"id": "1",
"name_definition": "black",
"price": 1
},
{
"id": "2",
"name_definition": "white",
"price": 0
},
{
"id": "3",
"name_definition": "Green",
"price": 5.95
}
],
"Size": [
{
"id": "1",
"name_definition": "30",
"price": 21
},
{
"id": "2",
"name_definition": "15",
"price": 4
},
{
"id": "3",
"name_definition": "10",
"price": 0
}
]
}
}
答案 0 :(得分:1)
最好的方法可能会像你提到的那样实现,如下所示:
{
"products": [
{
"id": 1,
"defaultColor": "examplecolor",
"defaultPrice": 5,
"currencySelected": "$",
"variations": [
{
"variationType": "Color",
"variationItem": "Black",
"variationPrice": 1,
"variationEffectType": "Add"
},
{
"variationType": "Size",
"variationItem": 30,
"variationPrice": 21,
"variationEffectType": "Add"
}
]
}
]
}
这种方式对于每个产品及其变体,您只需要访问产品数组中的单个对象,并且也很容易理解。还有一些建议,使用驼峰套管并避免在第一个字母键中加盖。< / p>