我有stringify JSON对象,我尝试更改它的属性值"quantity"
"[{"name":"Butter","image":"/static/images/items/dairy/butter.jpg",
"price":" 30 uah","quantity":"1","alias":"butter"},
{"name":"Chesse","image":"/static/images/items/dairy/cheese.jpg",
"price":" 60 uah","quantity":"1","alias":"chesse"}]"
所以我获得了属性值json[0].quantity
并尝试重写它
var quantity = parseInt(json[0].quantity);
json[0].quantity = String(quantity + 1);
但它不起作用。 "quantity"
属性保持不变。请帮忙
答案 0 :(得分:0)
我会尝试使用
将此json解析为javscript对象json = JSON.parse(json)
然后你可以试试你的旧代码,它应该可以解决。另外,要将它变回json,只需使用
JSON.stringify(json)
答案 1 :(得分:0)
不确定我的问题中的示例代码是否有效。
试试这个,你会发现它有效:
var json = [{
"name": "Butter",
"image": "/static/images/items/dairy/butter.jpg",
"price": " 30 uah",
"quantity": "1",
"alias": "butter"
}];
var quantity = parseInt(json[0].quantity);
json[0].quantity = String(quantity + 1);
console.log(json[0]);
输出:
Object {name: "Butter", image: "/static/images/items/dairy/butter.jpg", price: " 30 uah", quantity: "2", alias: "butter"}
如您所见,数量现在显示为2。
我不确定你为什么要将数值保存为字符串,但这是一个不同的主题。
答案 2 :(得分:0)
因为你有json字符串,你首先需要将它解析为json并增加数量属性,首先需要它来parseInt:
var jsonString = '[{"name ":"Butter","image":"/ static / images / items / dairy / butter.jpg ","price":"30 uah","quantity":"1","alias":"butter"},{"name":"Chesse","image":"/static/images/items/dairy/cheese.jpg","price":" 60 uah","quantity":"1","alias":"chesse"}]';
console.log(JSON.stringify(jsonString))
var product = JSON.parse(jsonString);
product[0].quantity = parseInt(product[0].quantity)+1;
alert(product[0].quantity);