I want Ruby to load JSON in Array from a file

Asked 1 years ago, Updated 1 years ago, 73 views

I would like to include the following data in the json file in Ruby as Hash in Array.

When I read it in JSON.load, it reads as nilClass, and when I read it in read, it becomes String, so I'm having trouble with it.Is there a good way to read it?

JSON files (hoge.json)

[
  {
    "name": "hoge",
    "age"—18
  },
  {
    "name": "hoge",
    "age"—18
  },
...
]

ruby json

2022-09-30 16:58

1 Answers

I think it would be good to read the contents of the file as a string and then parse it.

require 'json'

json=File.read('hoge.json')
JSON.parse (json)

When loading with JSON.load, it's good to pass an object like IO like a file like this

require 'json'

File.open('hoge.json'){|f|JSON.load(f)}


2022-09-30 16:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.