This is a card in Dave's Virtual Box of Cards.

Ruby: read a JSON file

Page created: 2025-07-24

back to ruby

This example reads a JSON file containing an array, parses it, joins the results, and writes them to a text file:

require 'json'
jsonf = File.read('names.json')
list = JSON.parse(jsonf)

# write the array as a comma-separated string
joined = list.join(',')
File.open('names.txt','w'){ |f| f.write(joined) }

This example reads an Emoji list JSON file and prints a list of the hexcodes from each emoji item, followed by a list of labels:

require 'json'

json = File.read('emoji.json')
em = JSON.parse(json)

hexes = em.map { |e| e['hexcode'] }
labels = em.map { |e| e['label'] }

puts hexes.join(',')
puts labels.join(',')

Structure of the JSON data used by the above example:

[
  {
    "hexcode":"1F1E6",
    "label":"regional indicator A",
    "unicode":"🇦"
  },
  ...
]

See also ruby-print-columns for another JSON example