簡體   English   中英

如何選擇鍵:JSON對象中使用的字符串格式的值對?

[英]How to select a key: value pair in string format used in a JSON object?

我想選擇長度,但是它是字符串形式。 與attribs.length相似,但未返回任何內容。

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

我曾嘗試將其拆分並重新加入,但是無論哪種方式我都無法獲得想要的東西。 我也嘗試過attribs [length]和attribs [“ length”],但無濟於事。

這是它的主要塊:

 { 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 } ] }, 

這是我嘗試獲取該數據的嘗試:

{{ result.activities[0].attribs["length"] }}

如果attribs是實際的javascript對象,並且您想要attribs.length的數值

var x = parseFloat(attribs.length.replace(/"/g,''));

由於length屬性周圍有一組引號,因此您可以使用JSON.parse將其解析為字符串。

JSON.parse(obj.attribs.length);

並將其轉換為數字,請使用parseInt() 這樣就變成了:

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

您的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); }); 

大家好! 我為以前沒有看到這個而感到尷尬,但是從我所看到的對象響應的下方開始有兩個key:value對,

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有最直接的答案,在我看來,這是干凈/准確/准確的答案,因此他接受了檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM