gpt4 book ai didi

javascript - 尝试将 json 响应字符串变量转换为对象但失败

转载 作者:行者123 更新时间:2023-11-30 19:54:45 25 4
gpt4 key购买 nike

json 响应返回(来自 ajax 函数):

{
"shoe_products":"{name: 'nike pegasus 35',data: [56.00,43.00,32.00], stack: 'Nike'},{name: 'adidas ultraboost',data: [32.00,34.00,35.00,0, 55.0],堆栈:'阿迪达斯'}“
}

这是我使用 alert(typeof data.myjson) 调试后的字符串。问题是,我无法将其转换为对象。

var myobj = JSON.parse(data.shoe_products); //this will return Unexpected token n in JSON at position 1

但是如果我执行下面的代码,它会作为一个对象返回。

var test = [{"shoe_products":"{name: 'nike pegasus 35',data: [56.00,43.00,32.00], stack: 'Nike'},{name: 'adidas ultraboost',data: [32.00,34.00,35.00,0,55.0], stack: 'Adidas'}"}];

Ajax 函数

 $.ajax({
type: "POST",
url: urlLinkHere,
data: { "year" : year },
success: function(data) {

var myobj = JSON.parse(data.shoe_products);

}
});

});

最佳答案

也许你可以考虑以下几点:

  1. 用双引号将 json 字符串中的任何“key”括起来:.replace(/([a-z]+)\w*c/gi, "\"$1\":")。这里的想法是匹配任何后跟 :(我们认为是键)的字符串,并将这些匹配用双引号引起来。
  2. 接下来,用[]将第1步的字符串包围起来,看到shoe_products中的数据实际上是一个数组(有shoe_products 字符串中的多个对象,由 ,)
  3. 分隔

所以,按照这些思路:

// Your input data
var test = [{"shoe_products":"{name: 'nike pegasus 35',data: [56.00,43.00,32.00], stack: 'Nike'},{name: 'adidas ultraboost',data: [32.00,34.00,35.00,0,55.0], stack: 'Adidas'}"}];

var shoe_products = test[0].shoe_products;

// The shoe_products data is organised as a list of data, so surround with [] brackets
// to achieve valid JSON array
var validJsonString = '[' + shoe_products
// Surround all json keys with double quotes. These are matched by any string followed by
// a colon
.replace(/([a-z]+)\w*:/gi, "\"$1\":")
// Replace any other single quote with double quotes
.replace(/'/gi,'"') + ']'


var jsonObject = JSON.parse(validJsonString);

console.log(jsonObject)

关于javascript - 尝试将 json 响应字符串变量转换为对象但失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com