本文介绍了在JavaScript中更改(重写)json对象的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串化的JSON对象,我试图在其中更改其属性"quantity"

I've got stringify JSON object in which I try to change value of it's property "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并尝试将其重写为

So I get property value json[0].quantity and try to rewrite it like that

var quantity = parseInt(json[0].quantity); json[0].quantity = String(quantity + 1);

var quantity = parseInt(json[0].quantity); json[0].quantity = String(quantity + 1);

但这是行不通的. "quantity"属性保持不变.请帮助

But it's doesn't work. "quantity" property stays constant. Please help

推荐答案

由于您拥有json字符串,因此您首先需要将其解析为json,并增加数量属性,首先需要使用它来parseInt:

since you have json string you first need to parse it in to json and to increment quantity property you first need it to 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);

这篇关于在JavaScript中更改(重写)json对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:02