2017-06-26 39 views
0

我是ruby的新手,並且在循環嵌套的哈希和數組時遇到困難。來自深層嵌套哈希和數組的循環特定值

說我有以下的JSON:

{ 
    "Resume":{ 
       .... data .... 
     }, 
     "StructuredXMLResume":{ 
     "ContactInfo":{ 
       .... data .... 
       } 
      ] 
     }, 
     "EmploymentHistory":{ 
      "EmployerOrg":[ 
       { 
        "EmployerOrgName":"ABC Corp.", 
        "PositionHistory":[ 
        { 
       .... data .... 
        ] 
       }, 
       { 
        "EmployerOrgName":"National Geo.", 
        "PositionHistory":[ 
        { 
      .... data .... 
          } 
         ] 

        } 
        ] 
       } 
      ] 
     } 

resume.["Resume"]["StructuredXMLResume"]["EmploymentHistory"]["EmployerOrg"][0]["EmployerOrgName"] 

給我ABC Corp.

resume.["Resume"]["StructuredXMLResume"]["EmploymentHistory"]["EmployerOrg"][1]["EmployerOrgName"] 

給我National Geo.

如何循環打印每EmployerOrgName

+0

我也應該使用'each'或'map'?我對兩者之間的差異感到困惑。 – cruisertom

回答

2

用途:

resume.["Resume"]["StructuredXMLResume"]["EmploymentHistory"]["EmployerOrg"].each do |employer_org| 
    puts employer_org["EmployerOrgName"] # or whatever you want to do with the employer_org hash 
end 
0

您可以使用一個枚舉,像每一個,任何「東西」,要麼是或表現得像一個數組/哈希對象,所以在這種情況下,你會想:

all_employerorgs = resume.["Resume"]["StructuredXMLResume"]["EmploymentHistory"]["EmployerOrg"] 
# which is an array of hashes that then you can iterate through 
# you could iterate directly on that but for readibility 
# I would always assign it to a var 
all_employerorgs.each do |employerorg| 
    puts employerorg['EmployerOrgName'] 
end