0

from this

["{\r\n  \"charge_type\": \"sports\",\r\n  \"amount\": 1000\r\n},{\r\n  \"charge_type\": \"servicing\",\r\n  \"amount\": 550\r\n}"]

to this

[{"charge_type"=>"sports", "amount"=> "1000"},{"charge_type"=>"servicing", "amount"=> "500"}]

I have tried this,

JSON.parse(["{\r\n  \"charge_type\": \"sports\",\r\n  \"amount\": 1000\r\n},{\r\n  \"charge_type\": \"servicing\",\r\n  \"amount\": 550\r\n}"].first)

But could not figure it out. Any help will be appreciated.

2
  • Why are you using a version of Ruby on Rails that has been unmaintained for many years and has open, unpatched security vulnerabilities? Commented Dec 30, 2022 at 11:50
  • 1
    That's because it's not valid JSON. Check it with a linter. Hint: Surround it with [ ... ]. For some reason you've done that external to the JSON string. Commented Dec 30, 2022 at 14:04

2 Answers 2

1

You are having problem because your json is not valid, your array [] is not wrapped around string, it need to be "[]" then it will work.

e.g your current json will give error

unexpected token at ',{
  "charge_type": "servicing",
  "amount": 550

but if your json is completely wrapped inside string like this (notice " around array)

my_json = "[{\r\n  \"charge_type\": \"sports\",\r\n  \"amount\": 1000\r\n},{\r\n  \"charge_type\": \"servicing\",\r\n  \"amount\": 550\r\n}]"

then you can do something like this

JSON.parse(my_json)

which will return

[{"charge_type"=>"sports", "amount"=>1000}, {"charge_type"=>"servicing", "amount"=>550}]
Sign up to request clarification or add additional context in comments.

Comments

1

It's not clear what you're trying to do with the [...].first part. What you really need is:

JSON.parse("[{\r\n  \"charge_type\": \"sports\",\r\n  \"amount\": 1000\r\n},{\r\n  \"charge_type\": \"servicing\",\r\n  \"amount\": 550\r\n}]")

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.