Search code examples
rubyredisunmarshalling

How to get a field on string data in Ruby for Redis?


I have a dataset with the name of table1 in Redis like below:

[
  {
    "column-name1": "10.1.10.1",
    "column-name2": "range(100,200)",
    "column-name3": "nam3"
  },
  {
    "column-name1": "2.2.2.2",
    "column-name2": "",
    "column-name3": "range(1024,+inf)"
  },
  {
    "column-name1": "1.1.1.1",
    "column-name2": "",
    "column-name3": "nam3"
  }
]

I want to get values of table1.. How can I do it?

How can I parse table1 in ruby to reach its values?


Solution

  • Frist, you should parse json data from stored string in Redis. For parsing json in Ruby you can do something like below:

    require "redis"
    require "json"
    
    red = Redis.new(host: "127.0.0.1", port: 6379, db: 1) <-- connect to redis
    
    table1 = red.get("table1") <-- get table1 value (stringified data)
    table1_json = JSON.parse(table1) <-- parse value to get a JSON object
    

    now you have your table1 data as a json object and you can iterate over its elements and get the values you want:

    for key in table1_json
        puts(key["column-name1"])
    end