简体   繁体   English

如何使用Ruby将字符串数组传递给JSON API Post

[英]How to pass array of strings to JSON API Post with Ruby

I have parsed a csv file into 3 different arrays. 我已经将一个csv文件解析为3个不同的数组。 Each column is an array- arr1 is the "name" column, arr2 is the "email" column, and arr3 is the "ID" column. 每个列都是一个数组-arr1是“名称”列,arr2是“电子邮件”列,而arr3是“ ID”列。

I am trying to make a post request to an API that accepts JSON. 我正在尝试向接受JSON的API发出发布请求。 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. 我需要同时发布每一行(因此arr1 [0],arr2 [0]和arr3 [0]),以确保它们都与一个联系人绑定。 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). 我可以创建一个arr1.each语句,但这将省略电子邮件字段(arr2)和id字段(arr3)。 How can I loop over 3 or more arrays? 如何循环3个或更多阵列?

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. 这是CSV文件中联系人或任何记录的典型格式。 Read the file using CSV and you can get an array containing records. 使用CSV读取文件,您可以获得包含记录的数组。 Tell CSV to not use the headers in each row's data and you'll get arrays of arrays. 告诉CSV不要在每一行的数据中使用标题,您将获得数组数组。

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. 到那时,通过将to_json应用于整个记录数组,将捆绑在一起的每个联系人的信息发送起来很简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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