Home>

I want to put each value of deeply nested json (hash) data in the DB, but it doesn't go well.

data =
{
{"id" =>"1," country_id "=>" 169 "," country_name "=>" England "," league_id "=>" 62 ",
"lineup" =>{
"home" =>{"starting_lineups" =>[], "substitutions" =>[]},
"away" =>{"starting_lineups" =>[], "substitutions" =>[]}
},
"statistics" =>[]},
.
Omission
.
{"id" =>"20", "country_id" =>"169", "country_name" =>"England", "league_id" =>"62",
"lineup" =>{
"home" =>{"starting_lineups" =>[], "substitutions" =>[]},
"away" =>{"starting_lineups" =>[], "substitutions" =>[]}
},
"statistics" =>[]}
}


I want to put the json data in the above array in a table called tables.
What we are doing now is that the "lineup =>"value is nested, so

home = nil
away = nil
data.each do | detail |
    b = detail ['lineup']
    home = b.assoc ('home'). pop
    away = b.assoc ('away'). pop
 end


And the values ​​of the keys home and away are put in the variables home and away, respectively.
And I want to put home, away and other hash values ​​together in a table called tables, so I use the zip method to put them together and use the create method in the block.

team_data.zip (home, away) .each do | detail1, detail2, detail3 |
Table.create (match_id: detail1 ['match_id'], country_id: detail1 ['country_id'],
country_name: detail1 ['country_name'], league_id: detail1 ['league_id'],
lineup_h: detail2 ['starting_lineups'], lineup_a: detail3 ['starting_lineups'],
substitute_h: detail2 ['substitutions'], substitute_a: detail3 ['substitutions']
end


The code is written as follows.
Since the above code is defined as task in the rake file, if you type the rake task command on the console screen and look at the log, you will see no implicit conversion of String into Integer error, and the angry part is the block variable detail2 This is the place where the values ​​of home and away such as detail3 are entered in the column.
As for the zip method, it is something that I find and use on my own, and there is still an ambiguous aspect of how to use it, so I do not know why the error has occurred. What is the problem?
By the way, all column types are defined as strings, and starting_lineups and substitutions values ​​are as you see, but multiple values ​​will be entered as an array.
I hope it will be a little longer. Thank you.

  • Answer # 1

    I feel like JSON is not JSON ... First,

    data =
    {

    is

    data =
    [
    Is

    wrong?

    Also, the meaning of the errorno implicit conversion of String into Integermeans that the string came where the numeric value should come, so it tried to convert but failed.

    This is probably because detail2 is an array, but it was accessed like Hash likedetail2 ['starting_lineups'].

Related articles