如何选择JSON对象中使用的字符串格式的键:值对?

时间:2015-10-15 03:43:51

标签: javascript json object key

我想选择长度,但它是字符串形式。类似attribs.length的东西,但什么也没有返回。

pyplot.show()

我试过拆分它并重新加入它,但无论哪种方式我都得不到我想要的东西。 我也尝试过attribs [length]和attribs [“length”],但无济于事。

以下是它的主要部分:

attribs: {
    "length": ""4"",
    "nightride": "null"
}

这是我尝试获取数据的有意义的尝试:

{ places: [ { city: "Boise", state: "Idaho", country: "United States", name: "Elk Meadows", parent_id: null, unique_id: 1637, directions: ""From Boise's north end (at the intersection of Hill and Bogus Basin roads), travel north up Bogus Basin road about 16.5 miles.the pavement ends at lower (main)parking lot near Bogus Creek Lodge. Proceed on the Boise Ridge Rd. Where the sandy surface turns to pavement as it leavesthe main ridge rd.and splitsright, up through a series of switch backs to the Pioneer Lodge milage starts here", lat: 43.764, lon: -116.10324, description: null, date_created: null, children: [ ], activities: [{ name: "Elk Meadows", unique_id: "1-118", place_id: 1637, activity_type_id: 5, activity_type_name: "mountain biking", url: "http://www.singletracks.com/item.php?c=1&i=118", attribs: { "length": ""4"", "nightride": "null" }, description: "ride east up behind Pioneer Lodge past the tennis courts on your left. the double track becomes more defined", length: 4, activity_type: { created_at: "2012-08-15T16:12:35Z", id: 5, name: "mountain biking", updated_at: "2012-08-15T16:12:35Z" }, thumbnail: "http://images.singletracks.com/2010/11/Elk-Meadows-on-the-Ranier-0.jpg", rank: null, rating: 3 } ] },

4 个答案:

答案 0 :(得分:2)

如果attribs是一个实际的javascript对象,并且你想要attribs.length的数值

UIScrollView

答案 1 :(得分:1)

由于length属性周围有一组额外的引号,您可以使用JSON.parse将其解析为字符串。

JSON.parse(obj.attribs.length);

要将其转换为数字,请使用parseInt()。所以一切都变成了:

var length = parseInt(JSON.parse(obj.attribs.length), 10);

答案 2 :(得分:1)

您的JSON无效。 JSON应始终为单个数组或单个对象

这是一个合适的JSON:

{
    "attribs": {
        "length": "4",
        "nightride": "null"
}

所以,你可以:

  1. 写入API提供商的支持或停止使用此API。在99%的情况下,这是一个合适的解决方案。

  2. 做一些非常糟糕的黑客攻击。在任何情况下我都不建议这样做。但是,这可以解决问题。就像这样:

    .done(function(data) {
         data = "{" + data.replace("\"\"", "\"") + "}";
    
        var obj = JSON.parse(data);
        alert(obj.attribs.length);
    });
    

答案 3 :(得分:0)

大家好!我之前没有看到这个问题,我感到很尴尬,但有两个关键:价值对进一步降低了对象响应的范围,我正在寻找,

attribs: { "length": ""4"", "nightride": "null" },

还有另一个关键:标准值格式的距离值对我们都知道并喜欢:

attribs: { "length": ""4"", "nightride": "null" }, description: "ride east up behind Pioneer Lodge past the tennis courts on your left. the double track becomes more defined", length: 4,

强调

length: 4,

当然,我把我的记法指向了那一点。

Jaromanda X拥有最直接的,在我看来,干净/精确/准确的答案,所以他接受了检查。