我想在jQuery中分离PHP JSON字符串

I want to seperate the PHP JSON string in jQuery

本文关键字:PHP JSON 字符串 分离 jQuery      更新时间:2023-09-26

我在分离json数组结果时遇到问题。当我在jquery中提醒json结果时,它会返回以下数组。

{"productid":"17","product_quantity":"2"}{"productid":"9","product_quantity":"1"}

现在我想将不同变量中的每个值分开。

提前Thanx。

这不是一个有效的json字符串。首先,您可以将输入转换为json字符串。然后,您可以使用JSON.parse来获取js数组。

例如

首先你需要这样做:

input = '[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]'

然后:

input_array = JSON.parse(input)

可能是服务器返回的字符串不是有效的JSON。一个有效的例子是:

[{"productid":"17","product_quantity":"2"},{"productid":"9","product_quantity":"1"}]

你是如何创建json的?既然你标记了PHP,正确的方法(如果你有一个数组)是这样的,它会返回有效的JSON,JS可以处理:

echo json_encode($array);

您提供的json格式错误。我想这是个拼写错误。

使用JSON.parse转换为javascript对象。

var jsonString = [{"productid":"17","product_quantity":"2"}, {"productid":"9","product_quantity":"1"}];
var data = JSON.parse(jsonString);
console.log(data[1].productid);  // 9

但我不知道你的意思。"现在我想把不同变量中的每个值都分开。"

为什么?无论如何你都可以这么做。尽管我确实说不要。但你问了。

data.forEach(function(item){
    window["productid"+item.productid] = item.product_quantity;
});

将在全球范围中为您提供2个变量

console.log(productid17); // "2"
console.log(productid9); // "1"