Reputation: 150
I have the following arrays and I want to add this to a json file.
hrefs2 = hrefs.select { |key, value| key.to_s.match("xxxx") && !key.to_s.match("yyyy") } images2 = images.select { |key, value| key.to_s.match("hbeu") } File.open("my_file.json","w") do |f| f.write({ :links => hrefs2, :images => images2}.to_json)
the problem I have is that in my json file the output looks like this
{ "links":[link1,link2] "images":[image1,image2] }
What I would actually want for my output is something like this
{ "links":"link1", "images":"image1", "links":"link2", "images":"image2" }
Is this something that would be easy to do in ruby?
thank you
Upvotes: 0
Views: 52
Reputation: 1044
As it was mentioned in a comment the JSON you want to generate has conflicting keys. This will give you a valid JSON that I think is closer to what you're looking for (as long as the number of links is the same as the number of images):
hrefs2 = [:link1, :link2]
images2 = [:image1, :image2]
my_json = hrefs2.zip(images2).map do |(link, image)|
{link: link, image: image}
end.to_json
puts my_json
#>> [{"link":"link1","image":"image1"},{"link":"link2","image":"image2"}]
Upvotes: 1
Reputation: 2663
I would just write some code to parse the JSON into whatever format you'd like.
Also, as mentioned in the comments I would keep in mind that if you're storing it in that format you would most definitely want to convert it back if you're wanting to really integrate with any of the built-in to hash methods.
Upvotes: 0