在Ruby中转换为JSON

mutmk8jj  于 2023-03-22  发布在  Ruby
关注(0)|答案(1)|浏览(209)

我在一个文本文件中有以下几行,并使用File. foreach进行迭代。我想创建一个JSON格式的这些。我如何编码?当我打印哈希值时,Camaro覆盖了Mustang信息。

#textfile#
Blue   A   Mustang
Red    B   Camaro   

File.each("textfile") di |line|
  fields = line.split
  field1 = fields.first
  field2 = fields.[1]
  field3 = fields.last
  puts field1
  puts field2
  puts field3
  myhash['color'] = field1
  myhash['parkingspot'] = field2 
  myhash['car'] = field3 
end

提前感谢!杰克
我试着推到哈希

kqqjbcuj

kqqjbcuj1#

在代码中,有一个名为myhashHash,它有三个索引:colorparkingspotcar,每次覆盖这三个索引的值时,都要遍历文件的每一行。每个数组都包含这样一个Hash。然后我们可以使用JSON.generate方法将汽车数组转换为JSON字符串,如下所示:

require 'json'

cars = []

File.foreach("textfile") do |line|
  fields = line.split
  car = {}
  car['color'] = fields.first
  car['parkingspot'] = fields[1]
  car['car'] = fields.last
  cars << car
end

puts JSON.generate(cars)

输出[{"color":"Blue","parkingspot":"A","car":"Mustang"},{"color":"Red","parkingspot":"B","car":"Camaro"}]
edit:如果你想用parkingspot作为每辆车的关键字,你可以这样做:

require 'json'

cars = {}

File.foreach("textfile") do |line|
  fields = line.split
  car = {}
  car['color'] = fields.first
  car['car'] = fields.last
  cars[fields[1]] = car
end

puts JSON.generate(cars)

输出{"A":{"color":"Blue","car":"Mustang"},"B":{"color":"Red","car":"Camaro"}}

相关问题