Parsing a JSON string in Ruby

2018-12-31 21:20发布

I have a string that I want to parse in Ruby:

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'

Is there an easy way to extract the data?

标签: ruby json
7条回答
公子世无双
2楼-- · 2018-12-31 21:55

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so:

require 'json'
JSON.parse(json_string)

If you’re using an older Ruby, you may need to install the json gem.


There are also other implementations of JSON for Ruby that may fit some use-cases better:

查看更多
孤独总比滥情好
3楼-- · 2018-12-31 22:01

As of Ruby v1.9.3 you don't need to install any Gems in order to parse JSON, simply use require 'json':

require 'json'

json = JSON.parse '{"foo":"bar", "ping":"pong"}'
puts json['foo'] # prints "bar"

See JSON at Ruby-Doc.

查看更多
弹指情弦暗扣
4楼-- · 2018-12-31 22:03

Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example
require "rubygems"
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
  p shop["id"]
end
查看更多
旧时光的记忆
5楼-- · 2018-12-31 22:06

That data looks like it is in JSON format.

You can use this JSON implementation for Ruby to extract it.

查看更多
还给你的自由
6楼-- · 2018-12-31 22:14

It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:

JSON.parse(string)
查看更多
萌妹纸的霸气范
7楼-- · 2018-12-31 22:15

This is a bit late but I ran into something interesting that seems important to contribute.

I accidentally wrote this code, and it seems to work:

require 'yaml'
CONFIG_FILE = ENV['CONFIG_FILE'] # path to a JSON config file 
configs = YAML.load_file("#{CONFIG_FILE}")
puts configs['desc']['someKey']

I was surprised to see it works since I am using the YAML library, but it works.

The reason why it is important is that yaml comes built-in with Ruby so there's no gem install.

I am using versions 1.8.x and 1.9.x - so the json library is not built in, but it is in version 2.x.

So technically - this is the easiest way to extract the data in version lower than 2.0.

查看更多
登录 后发表回答