I am trying to write/append some data in a JSON file using ruby. I am facing issues while writing data in JSON file in proper format. I have created and stored my values in temphash. I want to append the content of temphash in existing JSON file. I am doing it in following way:
tempHash = {"Group_Name" => @GroupName, "Group_Logo_Code" => @GroupLogoCode }
json = File.read('public/group.json')
secondJsonArray = JSON.parse(json)
secondJsonHash = Hash[*secondJsonArray]
jsonHash = []
jsonHash << secondJsonHash
jsonHash << tempHash
File.open("public/group.json","w") do |f|
f.puts JSON.pretty_generate(jsonHash)
end
This is creating malformed JSON. I am not getting the JSON in expected format
Below is what I expect:
[
{
"Group_Name": "Group Name",
"Group_Logo_Code": "Group Logo code"
},
{
"Group_Name": "Group Name",
"Group_Logo_Code": "Group Logo code"
},
{
"Group_Name": "Group Name",
"Group_Logo_Code": "Group Logo code"
},
]
Below is what I am getting:
[
{
"{\"{\\\"Group_Name\\\"=>\\\"Group Name\\\", \\\"Group_Logo_Code\\\"=>\\\"Group Logo code\\\"}\"=>{\"Group_Name\"=>\"Group Name\", \"Group_Logo_Code\"=>\"Group Logo code\"}}": {
"Group_Name": "Group Name",
"Group_Logo_Code": "Group Logo code"
}
},
{
"Group_Name": "Group Name",
"Group_Logo_Code": "Group Logo code"
}
]
Please let me know if there is any better way to do this. Can anyone please help me resolve this issue. Thanks in advance.