简体   繁体   中英

How to pass array of strings to JSON API Post with Ruby

I have parsed a csv file into 3 different arrays. Each column is an array- arr1 is the "name" column, arr2 is the "email" column, and arr3 is the "ID" column.

I am trying to make a post request to an API that accepts JSON. I need each row (So arr1[0],arr2[0], and arr3[0]) to be posted at the same time to ensure they all get tied to one contact. Then the request should continue looping until there are no records left to be added. The code I have so far is below:

         uri= HTTParty.post("https://www.surveys.com/api/v2/add-contact",
    :basic_auth => auth,
    :headers => { 'ContentType' => 'application/json' },
    :body => {
      "name" => arr1[0],
      "email" => arr2[0],
      "id" => arr3[0]
    }
  )

While this would work to create one contact, I am drawing a blank on how to loop through the contact. I could create an arr1.each statement, but that would leave out the email field (arr2) and id field(arr3). How can I loop over 3 or more arrays?

Thanks for the help.

Without having seen the data it's impossible to say for sure, but I'll suggest that instead of parsing into three columns, you need to leave your data as rows, since it sounds like each contact is a row.

That's the typical format for a contact, or any record, in a CSV file. Read the file using CSV and you can get an array containing records. Tell CSV to not use the headers in each row's data and you'll get arrays of arrays.

At that point it will be simple to send each contact's information bundled together, by applying to_json to the entire array of records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM