Method: Faker::Json.add_depth_to_json

Defined in:
lib/faker/default/json.rb

.add_depth_to_json(json: shallow_json, width: 3, options: { key: 'Name.first_name', value: 'Name.first_name' }) ⇒ Hash{String => String}

Produces a random nested JSON formatted string that can take JSON as an additional argument.

Examples:

json = Faker::Json.shallow_json(width: 3, options: { key: 'Name.first_name', value: 'Name.last_name' })
puts json # =>
  {"Alisha":"Olson","Everardo":"DuBuque","Bridgette":"Turner"}

json2 = Faker::Json.add_depth_to_json(json: json, width: 2, options: { key: 'Name.first_name', value: 'Name.last_name' })
puts json2 # =>
  {"Alisha":{"Daisy":"Trantow","Oda":"Haag"},
   "Everardo":{"Javier":"Marvin","Eliseo":"Schuppe"},
   "Bridgette":{"Jorge":"Kertzmann","Lelah":"MacGyver"}}

 json3 = Faker::Json.add_depth_to_json(json: json2, width: 4, options: { key: 'Name.first_name', value: 'Name.last_name' })
   puts json3 # =>
     {"Alisha":
       {"Daisy":
         {"Bulah":"Wunsch","Cristian":"Champlin","Lester":"Bartoletti","Greg":"Jacobson"},
        "Oda":
          {"Salvatore":"Kuhlman","Aubree":"Okuneva","Larry":"Schmitt","Velva":"Gibson"}},
      "Everardo":
        {"Javier":
          {"Eduardo":"Orn","Laila":"Kub","Thad":"Legros","Dion":"Wilderman"},
        "Eliseo":
          {"Olin":"Hilpert","Marisa":"Greenfelder","Karlee":"Schmitt","Judd":"Larkin"}},
      "Bridgette":
        {"Jorge":
          {"Eloy":"Pfeffer","Kody":"Hansen","Paxton":"Lubowitz","Abe":"Lesch"},
        "Lelah":
          {"Rick":"Wiza","Bonita":"Bayer","Gardner":"Auer","Felicity":"Abbott"}}}

Parameters:

  • json (Hash{String => String}) (defaults to: shallow_json)

    Specifies a Json.shallow_json and uses its keys as keys of the nested JSON.

  • width (Integer) (defaults to: 3)

    Specifies the number of nested key-value pairs.

  • options (Hash) (defaults to: { key: 'Name.first_name', value: 'Name.first_name' })

    Specifies a Faker gem class to use for nested keys and for values, respectably. options_hash = Class.method, value: Class.method

Returns:

  • (Hash{String => String})

Available since:

  • 1.9.2



71
72
73
74
75
76
77
78
79
80
# File 'lib/faker/default/json.rb', line 71

def add_depth_to_json(json: shallow_json, width: 3, options: { key: 'Name.first_name', value: 'Name.first_name' })
  options[:key] = "Faker::#{options[:key]}"
  options[:value] = "Faker::#{options[:value]}"

  hash = JSON.parse(json)
  hash.each_key do |key|
    add_hash_to_bottom(hash, [key], width, options)
  end
  JSON.generate(hash)
end