2

I'm trying to convert some API response data into a Ruby hash or array so I can more easily work with it. Here's the JSON string being returned by the API:

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

I believe that is a JSON array? 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

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.

6
  • What specifically are you showing us? What you've shown is an actual array of hashes. Commented Jun 15, 2015 at 16:09
  • 1
    JSON.parse is usually the way to do it. What is at position 1511 in your input? Commented Jun 15, 2015 at 16:13
  • what I'm showing you is a string. It looks like an array of hashes, and I think that's what i would like it to be. Commented Jun 15, 2015 at 16:13
  • I think I must have some extra whitespace or something in my JSON. I manually trimmed it down and tried the JSON.parse and it works. Commented Jun 15, 2015 at 16:17
  • 2
    Strings have quotes around them, that's what I'm saying--it's not clear what you actually have. If I put quotes around this (and escape the double-quotes) JSON.parse works just fine. Commented Jun 15, 2015 at 16:20

2 Answers 2

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

JSON.parse(array)
Sign up to request clarification or add additional context in comments.

4 Comments

You might want to run this code to see an error. What's the point of supplying a non-string object to JSON.parse?
Yes, we need to parse it JSON.parse(array.to_s)
@AmitSuroliya But he's saying he already has a string; you're taking a Ruby array of hashes, turning it into a string, then turning it back into a Ruby array of hashes.
You might also want to run JSON.parse(array.to_s) to see another error.
0

My question did not show the full string I was trying to JSON.parse. I only put what I was trying to parse. I accidentally left some floating data before the JSON part of my string. Now that I have deleted that, it is working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.