2016-07-15 57 views
-2

方案客戶端進行GET請求的響應是在一個JSON格式像這樣的應用正則表達式表達爲JSON響應數據

 var data = { 
    "enabled": true, 
    "state": "schedule", 
    "schedules": [ 
     { 
     "rule": { 
     "start": "2014-06-29T12:36:26.000", 
     "end": "2014-06-29T12:36:56.000", 
     "recurrence": [ 
     "RRULE:FREQ=MINUTELY" 
     ] 
     }, 
     "wifi_state_during_rule": "disabled", 
     "end_state": "enabled" 
     } 
    ], 
    "calculated_wifi_state_now": "disabled", 
    "time_of_next_state_change": [ 
     "2014-07-08T18:56:56.000Z", 
     "2014-07-08T18:57:56.000Z" 
    ] 
}; 

對於此示例的目的,我所存儲的結果在一個變量被稱爲「數據」。 我的正則表達式表達式是:

checkPattern = /"\w+\"(?=:)/ //all keys "keyname": ... 

基本IDEIA這裏它只是爲了讓鍵名,除了因爲JSON的鍵名的的定義是對象或數組......和裏面「鍵名」:這就是爲什麼我m試圖使用上面的正則表達式。

我甚至想過用遞歸函數做這件事,但沒有工作。

+0

爲什麼要使用正則表達式呢? Json字符串可以很容易地變成javascript,c#,Java和其他許多語言中的實際對象。真的不需要使用正則表達式。所以請詳細說明對正則表達式的需求,或者做一些研究來將它變成一個對象。信息在那裏。 –

+0

這裏的重點不是使用正則表達式。 我想只提取名稱,甚至認爲它們是嵌套的。 我用測試目的的正則表達式 – Eudes

回答

0

這會給你所有的keys的比賽:

\"(\w+)(?:\"\:)

https://regex101.com/r/iM9wB3/2

編輯與多個keys在一行上工作。

+0

如果一行上有多個鍵,這不起作用。 '+'太貪婪了。 – 4castle

1

你永遠不應該用正則表達式解析非規則結構。

只是從解析的json對象收集你想要的東西。
只要運行data = JSON.parse(json_string)用於解析它

function getKeysRecursive(obj) { 
    var result = []; 
    for (var key in obj) { 
    result.push(key); 
    if (typeof obj[key] == 'object') { 
     result = result.concat(getKeysRecursive(obj[key])); 
    } 
    } 
    return result; 
} 

getKeysRecursive(({ 
    "enabled": true, 
    "state": "schedule", 
    "schedules": [ 
     { 
     "rule": { 
     "start": "2014-06-29T12:36:26.000", 
     "end": "2014-06-29T12:36:56.000", 
     "recurrence": [ 
     "RRULE:FREQ=MINUTELY" 
     ] 
     }, 
     "wifi_state_during_rule": "disabled", 
     "end_state": "enabled" 
     } 
    ], 
    "calculated_wifi_state_now": "disabled", 
    "time_of_next_state_change": [ 
     "2014-07-08T18:56:56.000Z", 
     "2014-07-08T18:57:56.000Z" 
    ] 
})) 

// ["enabled", "state", "schedules", "0", "rule", "start", "end", "recurrence", "0", "wifi_state_during_rule", "end_state", "calculated_wifi_state_now", "time_of_next_state_change", "0", "1"] 

您可以過濾它們,排序,排除數字鍵......你需要什麼所有。

+1

謝謝先生,那是我真正需要的。 – Eudes

0

你不需要這個正則表達式。 Javascript有一個內置的函數來提取對象的關鍵字名稱。

實施例:

使用Object.keys();

var data = { 
    "enabled": true, 
    "state": "schedule", 
    "schedules": [ 
     { 
     "rule": { 
     "start": "2014-06-29T12:36:26.000", 
     "end": "2014-06-29T12:36:56.000", 
     "recurrence": [ 
     "RRULE:FREQ=MINUTELY" 
     ] 
     }, 
     "wifi_state_during_rule": "disabled", 
     "end_state": "enabled" 
     } 
    ], 
    "calculated_wifi_state_now": "disabled", 
    "time_of_next_state_change": [ 
     "2014-07-08T18:56:56.000Z", 
     "2014-07-08T18:57:56.000Z" 
    ] 
}; 

然後

console.log(Object.keys(data)); 

應打印

["enabled","state","schedules","calculated_wifi_state_now","time_of_next_state_change"]

證明:http://codepen.io/theConstructor/pen/zBpWak

現在所有的對象鍵被存儲在一個數組..

希望這有助於