在Ruby中解析JSON字符串 [英] Parsing a JSON string in Ruby

查看:172
本文介绍了在Ruby中解析JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在Ruby中解析的字符串:

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?

推荐答案

这看起来像 JavaScript对象表示法(JSON).您可以解析驻留在某些变量中的JSON,例如json_string,就像这样:

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)

如果您使用的是较旧的Ruby,则可能需要安装 json宝石.

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

还有其他针对JSON的JSON实现,可能更适合某些用例:

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

  • YAJL C Bindings for Ruby
  • JSON::Stream

这篇关于在Ruby中解析JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆