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

时间:2019-01-10 03:51:18

标签: javascript php json ajax

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], stack: 'Adidas'}" }

这是我使用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 个答案:

答案 0 :(得分:1)

也许您可以考虑以下内容:

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

因此,遵循以下原则:

// 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)