如何通过特定的单词从JSON文件中进行grep和排序?

时间:2014-02-04 14:21:44

标签: ruby json

我有以下JSON文件:

{
  "opscenter_adhoc_2014-02-03-12-34-16-UTC": {
    "keyspaces": {
      "test": {
        "nodes": [
          "10.242.214.188",
          "10.62.77.47",
          "10.244.15.39"
        ],
        "cfs": {
          "test": "/var/lib/cassandra/data/test/test/snapshots/opscenter_adhoc_2014-02-03-12-34-16-UTC"
        }
      }
    },
    "id": "adhoc",
    "time": 1391430856
  },
  "opscenter_adhoc_2014-02-03-13-16-04-UTC": {
    "keyspaces": {
      "test": {
        "nodes": [
          "10.242.214.188",
          "10.62.77.47",
          "10.244.15.39"
        ],
        "cfs": {
          "test": "/var/lib/cassandra/data/test/test/snapshots/opscenter_adhoc_2014-02-03-13-16-04-UTC"
        }
      }
    },
    "id": "adhoc",
    "time": 1391433364
  },
  "opscenter_adhoc_2014-02-03-11-32-06-UTC": {
    "keyspaces": {
      "test": {
        "nodes": [
          "10.242.214.188",
          "10.62.77.47",
          "10.244.15.39"
        ],
        "cfs": {
          "test": "/var/lib/cassandra/data/test/test/snapshots/opscenter_adhoc_2014-02-03-11-32-06-UTC"
        }
      }
    },
    "id": "adhoc",
    "time": 1391427126
  }

我希望opscenter_adhoc_2014-02-03-11-32-06-UTC仅在2014-02-03-11-32-06-UTC是备份时间戳的地方按grep文件,而不是按时间戳对列表进行排序以获取最新的时间戳。 使用

在Ruby中尝试
File.readlines("/tmp/out.txt").grep(/opscenter_adhoc/) 

返回所有字符串,但我只需要opscenter_adhoc_TIMESTAMP列表

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你希望得到排序日期。你走了:

require 'json'
JSON.parse(File.read('/tmp/qq.json')).keys.sort

# ⇒ => [
#        [0] "opscenter_adhoc_2014-02-03-11-32-06-UTC",
#        [1] "opscenter_adhoc_2014-02-03-12-34-16-UTC",
#        [2] "opscenter_adhoc_2014-02-03-13-16-04-UTC"
# ]