Jquery子串/拆分

时间:2015-11-03 15:12:10

标签: javascript jquery substring

$("#ELEMENT").TEXT()正在给我和html字符串。

<div id="ELEMENT">
{
    "products": [
        {
            "TPNB": "52260983",
            "name": "name1",
            "price": 0.89,
            "quantity": 1
        },
        {
            "TPNB": "73559869",
            "name": "name2",
            "price": 1.1,
            "quantity": 1
        },
        {
            "TPNB": "51447540",
            "name": "Tesco Dijon Mustard 185g",
            "price": 0.55,
            "quantity": 1
        },
        {
            "TPNB": "61227739",
            "name": "name3150ml",
            "price": 0.6,
            "quantity": 1
        },
        {
            "TPNB": "56925638",
            "name": "Tesco Chicken Thighs 1kg",
            "price": 2.5,
            "quantity": 2
        }
    ]
}
</div>

我想将此Array提取到以下索引

  1. "TPNB":"52260983","name":"name1","price":0.89,"quantity":1
  2. "TPNB":"52260983","name":"name2","price":0.89,"quantity":1
  3. "TPNB":"56925638","name":"name13","price":2.5,"quantity":2

4 个答案:

答案 0 :(得分:0)

var parsedJson = JSON.parse($("#ELEMENT").text())
var finalArray = new Array()
for (var i in parsedJson.products)
{
    finalArray.push(parsedJson.products[i]);
}
for (var i in finalArray)
{
    console.log(JSON.stringify(finalArray[i]).replace("{", "").replace("}", ""))  
}

之后你可以这样访问属性

finalArray[0].TPNB
finalArray[0].name
finalArray[0].price
finalArray[0].quantity

完整代码打开浏览器控制台并查看此http://jsfiddle.net/5wd29qch/1/

答案 1 :(得分:0)

如果文本是有效的json,您可以解析它并获得所需数组的products属性:

var raw = $("#ELEMENT").text(),
    parsed = JSON.parse(raw),
    products = parsed.products;

console.log(products);
console.log(products[0]);
console.log(products[1]);
console.log(products[2]);

答案 2 :(得分:0)

    var jsonData = // ur data from .text()
    var productData = JSON.parse(jsonData);
    var productRows = productData.products;
    for(var i = 0; i < productRows.length; i++)
    {
          alert(productRows[i]);
    }

答案 3 :(得分:0)

试试这个:

var json = $.parseJSON($('#ELEMENT').text());

json.products.map(function(v, i){
    console.log(JSON.stringify(v).replace('{','').replace('}',''));
});

<强>输出:

"TPNB":"52260983","name":"name1","price":0.89,"quantity":1
"TPNB":"73559869","name":"name2","price":1.1,"quantity":1
"TPNB":"51447540","name":"Tesco Dijon Mustard 185g","price":0.55,"quantity":1
"TPNB":"61227739","name":"name3150ml","price":0.6,"quantity":1
"TPNB":"56925638","name":"Tesco Chicken Thighs 1kg","price":2.5,"quantity":2