【问题标题】:Create a specific json(Hash) from a csv using Ruby使用 Ruby 从 csv 创建特定的 json(Hash)
【发布时间】:2017-08-02 05:11:08
【问题描述】:

如果尝试将多面 CSV(带标题)创建为可用于帖子的 json,我将不胜感激。这是所需的 csv 和 JSON 格式。最终;我需要创建一个可能有 1、2 或许多传真机的位置。

csv

ID,Location Name,timezone,code,display,address,city,state,postalcode,country,faxlocation,faxnumber,(in)active
5,Location1,America/Chicago,bu,Building,1313 Mocking Bird Lane,The City,IL,999999,USA,Room 1; Room 2,111111111; 2222222222,active
8,Location2,America/New_York,bu,Building,2626 Humpty Dumpty Lane,Another City,NY,999999,USA,Room 1; Room 2; Room 3,111111111; 2222222222; 3333333333,active
32,Location3,America/Los_Angeles,bu,Building,3939 Big Bird Lane,Last City,CA,999999,USA,Room 1,111111111,active

json

{
    "resourceType": "Location",
    "id": "5",
     "description": "America/Chicago",
    "name": "Location1",
    "address": {
        "address": "1313 Mocking Bird Lane",
        "city": "The City",
        "state": "IL",
        "postalCode": "999999",
        "country": "USA"
    },
    "telecom": [
        {
           "system": "fax",
            "value": "1111111111",
            "use": "work",
            "extension": [
                {
                    "url": "displayValue",
                    "valueString": "Room 1"
                }
            ]
        },
        {
           "system": "fax",
            "value": "2222222222",
            "use": "work",
            "extension": [
                {
                    "url": "displayValue",
                    "valueString": "Room "
                }
            ]
        }
    ],
    "status": "active"
}

这里都需要

locations = CSV.read(csv)

locations.shift # remove header row
locations.each_index do |index|
    faxnumarrat = locations[index][10].to_s.delete(' ').split(';') #Take 10th index and turn it into an array
    faxlocarray = locations[index][11].to_s.delete(' ').split(';') #Take 11th index and turn it into an array

    # keys = ['loc1','loc2'] 
    # values = ['fax1','fax2']
   my_hash = Hash[faxnumarray.zip(faxlocarray)] # Combine locations and fax numbers

   my_hash.each do |key, value|

      @fax_hash = { 'system' => 'fax', 'value' => key, 'use' => 'work', 'extension' => [{ 'url' => 'automaticSend', 'valueBoolean' => false }, { 'url' => 'displayValue', 'valueString' => value }] } #Build up a hash using k,v.  ISSUE:  Only creates one fax.  Need to put all faxes associated no matter how many per location
    end
end

【问题讨论】:

    标签: arrays json ruby csv hash


    【解决方案1】:

    您可以open 而不是将整个 CSV 作为数组读取 或者创建一个new CSV 实例并传入一个选项来转换第一行 进入标题进入键以更轻松地访问行内的列;例如

    locations = CSV.open(csv, headers: true)
    
    location = locations.first
    # => #<CSV::Row "ID":"5" "Location Name":"Location1" "timezone":"America/Chicago" "code":"bu" "display":"Building" "address":"1313 Mocking Bird Lane" "city":"The City" "state":"IL" "postalcode":"999999" "country":"USA" "faxlocation":"Room 1; Room 2" "faxnumber":"111111111; 2222222222" "(in)active":"active">
    
    location["Location Name"]
    # => "Location1"
    

    将标题作为我们可以使用的键,然后我们可以使用 那些旧的价值观,同时也建立了一个你在你的 问题示例

    locations = CSV.open(csv, headers: true)
    
    results = locations.map.with_index do |location, index|
      faxnumarray = location["faxnumber"].delete(' ').split(';') #Take 10th index and turn it into an array
      faxlocarray = location["faxlocation"].delete(' ').split(';') #Take 11th index and turn it into an array
    
      # keys = ['loc1','loc2']
      # values = ['fax1','fax2']
      my_hash = Hash[faxnumarray.zip(faxlocarray)] # Combine locations and fax numbers
    
      {
        "resourceType" => "Location",
        "id" => location["ID"],
        "description" => location["timezone"],
        "name" => location["Location Name"],
        "address" => {
          "address" => location["address"],
          "city" => location["city"],
          "state" => location["state"],
          "postalCode" => location["postalcode"],
          "country" => location["country"]
        },
        "telecom" => my_hash.map do |key, value|
          {
            'system' => 'fax',
            'value' => key,
            'use' => 'work',
            'extension' => [
              {
                'url' => 'automaticSend',
                'valueBoolean' => false
              },
              {
                'url' => 'displayValue',
                'valueString' => value
              }
            ]
          }
        end,
        "status" => location["(in)active"]
      }
    end
    
    results.to_json
    

    我尽可能重用了您的代码并制作了最后一个对象(返回的对象) 在map 块内类似于请求的哈希结果对象。使用map 而不是each 意味着它

    返回一个新数组,其中包含对 enum 中的每个元素运行一次 block 的结果。

    -- Module: Enumerable (Ruby 2_4_0)

    这会产生以下结果

    [
      {
        "resourceType": "Location",
        "id": "5",
        "description": "America/Chicago",
        "name": "Location1",
        "address": {
          "address": "1313 Mocking Bird Lane",
          "city": "The City",
          "state": "IL",
          "postalCode": "999999",
          "country": "USA"
        },
        "telecom": [
          {
            "system": "fax",
            "value": "111111111",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": "Room 1"
              }
            ]
          },
          {
            "system": "fax",
            "value": "2222222222",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": " Room 2"
              }
            ]
          }
        ],
        "status": "active"
      },
      {
        "resourceType": "Location",
        "id": "8",
        "description": "America/New_York",
        "name": "Location2",
        "address": {
          "address": "2626 Humpty Dumpty Lane",
          "city": "Another City",
          "state": "NY",
          "postalCode": "999999",
          "country": "USA"
        },
        "telecom": [
          {
            "system": "fax",
            "value": "111111111",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": "Room 1"
              }
            ]
          },
          {
            "system": "fax",
            "value": "2222222222",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": " Room 2"
              }
            ]
          },
          {
            "system": "fax",
            "value": "3333333333",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": " Room 3"
              }
            ]
          }
        ],
        "status": "active"
      },
      {
        "resourceType": "Location",
        "id": "32",
        "description": "America/Los_Angeles",
        "name": "Location3",
        "address": {
          "address": "3939 Big Bird Lane",
          "city": "Last City",
          "state": "CA",
          "postalCode": "999999",
          "country": "USA"
        },
        "telecom": [
          {
            "system": "fax",
            "value": "111111111",
            "use": "work",
            "extension": [
              {
                "url": "automaticSend",
                "valueBoolean": false
              },
              {
                "url": "displayValue",
                "valueString": "Room 1"
              }
            ]
          }
        ],
        "status": "active"
      }
    ]
    

    参考资料:

    【讨论】:

    • 简直太棒了。像冠军一样工作。感谢您带我去学校并教我一些新东西!
    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2021-08-11
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多