如何使用 Ruby on Rails 解析 JSON? [英] How do I parse JSON with Ruby on Rails?

查看:23
本文介绍了如何使用 Ruby on Rails 解析 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法来解析 JSON、提取值并将其写入 Rails 数据库中.

I'm looking for a simple way to parse JSON, extract a value and write it into a database in Rails.

特别是我正在寻找的是一种从 bit.ly API 返回的 JSON 中提取 shortUrl 的方法:

Specifically what I'm looking for, is a way to extract shortUrl from the JSON returned from the bit.ly API:

{
  "errorCode": 0,
  "errorMessage": "",
  "results":
  {
    "http://www.foo.com":
    {
       "hash": "e5TEd",
       "shortKeywordUrl": "",
       "shortUrl": "http://bit.ly/1a0p8G",
       "userHash": "1a0p8G"
    }
  },
  "statusCode": "OK"
}

然后将那个 shortUrl 写入与长 URL 关联的 ActiveRecord 对象中.

And then take that shortUrl and write it into an ActiveRecord object associated with the long URL.

这是我可以完全在概念上思考的事情之一,当我坐下来执行时,我意识到我有很多东西要学.

This is one of those things that I can think through entirely in concept and when I sit down to execute I realize I've got a lot to learn.

推荐答案

这些答案有点过时了.所以我给你:

These answers are a bit dated. Therefore I give you:

hash = JSON.parse string

Rails 应该自动为你加载 json 模块,所以你不需要添加require 'json'.

Rails should automagically load the json module for you, so you don't need to add require 'json'.

这篇关于如何使用 Ruby on Rails 解析 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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