将regex表达式应用于json响应数据

时间:2016-07-15 14:37:57

标签: javascript json regex

方案客户端发出GET请求,响应采用JSON格式,如此

<div class="main">
  <div class="aspect-ratio-1-1">
    <div>
      <img src="http://placehold.it/150x100">
     </div>
   </div>
</div>

为了这个例子的目的,我将结果存储在一个名为&#34; data&#34;的变量中。 我的正则表达式是:

     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"
    ]
};

这里的基本思想只是为了获取除了内部和对象或数组之外的关键名...因为JSON中keyname的定义是&#34; keyname&#34;:那是&#39; s为什么我试图使用上面的正则表达式。

我甚至考虑过使用递归函数执行此操作但不起作用。

3 个答案:

答案 0 :(得分: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 :(得分:0)

这将为您提供所有keys作为匹配项:

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

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

编辑在一行中使用多个keys

答案 2 :(得分:0)

你不需要正则表达式。 Javascript有一个内置函数来提取Object键名。

示例:

使用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

现在所有对象键都存储在一个数组中..

希望这有帮助