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

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

问题描述

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

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

有没有一种简单的方法来提取数据?

解决方案

这看起来像 JavaScript Object Notation (JSON).您可以解析驻留在某个变量中的 JSON,例如json_string,像这样:

需要'json'JSON.parse(json_string)

如果您使用的是较旧的 Ruby,则可能需要安装 json gem.><小时>

还有其他适用于 Ruby 的 JSON 实现可能更适合某些用例:

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?

解决方案

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:

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

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