简体   繁体   English

将JSON数组转换为Ruby Hash(具有哈希)

[英]convert JSON array to Ruby Hash (of hashes)

I'm trying to convert some API response data into a Ruby hash or array so I can more easily work with it. 我正在尝试将一些API响应数据转换为Ruby哈希或数组,以便更轻松地使用它。 Here's the JSON string being returned by the API: 这是API返回的JSON字符串:

[
  {
    "id": 2,
    "name": "TestThing",
    "token": "B2CA27221DB976E48248F26756289B91"
  },
  {
    "id": 3,
    "name": "AnotherTestThing",
    "token": "EF16E5F20B8463E48DBF3BA8F0E1102A"
  }
]

I believe that is a JSON array? 我相信这是一个JSON数组吗? I tried doing JSON.parse on that string, but got (JSON::ParserError)r/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/json/common.rb:148:in 'parse': 746: unexpected token at '1511 我尝试对该字符串执行JSON.parse ,但得到(JSON::ParserError)r/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/json/common.rb:148:in 'parse': 746: unexpected token at '1511

What is the best way to convert this into something I can easily work with? 将其转换为易于使用的最佳方法是什么? My real goal here is to iterate over the tokens returned. 我真正的目标是迭代返回的令牌。

require 'json'
array = '[
  {
    "id": 2,
    "name": "TestThing",
    "token": "B2CA27221DB976E48248F26756289B91"
  },
  {
    "id": 3,
    "name": "AnotherTestThing",
    "token": "EF16E5F20B8463E48DBF3BA8F0E1102A"
  }
]'

JSON.parse(array)

My question did not show the full string I was trying to JSON.parse . 我的问题没有显示我尝试使用JSON.parse的完整字符串。 I only put what I was trying to parse. 我只放入我解析的内容。 I accidentally left some floating data before the JSON part of my string. 我不小心在字符串的JSON部分之前留下了一些浮动数据。 Now that I have deleted that, it is working. 现在,我已经删除了它,它正在工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM