如何在本机中发布json数组

时间:2016-09-28 10:20:31

标签: react-native

我有一个像这样的JSON数组。我想通过fetch函数发布它。我没有找到任何关于这类问题的参考资料

[
    {
        "id": 824233,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 71,
        "comments": "Testing",
    },
    {
        "id": 824234,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 188,
        "comments": "test",
    },
    {
        "id": 824235,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 188,
        "comments": "Test",
    }
]

我想发布这个数组

4 个答案:

答案 0 :(得分:0)

你可以通过fetch

为循环发布并发布该数组的每个元素

答案 1 :(得分:0)

只需使用JSON.stringify(yourArray)将数组JSON对象转换为字符串,然后发布它。

var myArray = [
    {
        "id": 824233,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 71,
        "comments": "Testing",
    },
    {
        "id": 824234,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 188,
        "comments": "test",
    },
    {
        "id": 824235,
        "project_id": 1457,
        "issue_id": 123420,
        "activity_id": 188,
        "comments": "Test",
    }
];

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(myArray)
})

来源:https://facebook.github.io/react-native/docs/network.html#making-requests

答案 2 :(得分:0)

Ahmed是对的,你必须在使用fetch时对你的JSON进行字符串化。 JQuery和其他库会自动为您执行此操作。

我创建了一个小辅助函数,用于fetch,为您整理数据并具有其他内置魔法。

export default function headersFactory(jwtToken) {
  return function headers(method, data) {
    const header = {
      mode: 'cors',
      method,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    };
    if (jwtToken) header.headers.Authorization = `Bearer ${jwtToken.hash}`;
    if (data) header.body = JSON.stringify(data);
    return header;
  };
}

现在你可以这样称呼它:

import headersFactory from './headersFactory';

fetch('https://mywebsite.com/endpoint/', headersFactory(token)('post', myArray))
  .then(res => res.json())
  .then(data => console.log(data));

令牌参数用于身份验证并且是可选的,您也可以将其称为:

// this
const headers1 = headersFactory()('post', myArray);

// or this
const headers2 = headersFactory()('get');

// or this
const headers3 = headersFactory({ hash: 'asdfo3qi38094' })('delete');

答案 3 :(得分:0)

var item ={} // declaring object array
var array =[] // declaring array
item["id"] = '824233';              //adding object to the object array
item["project_id"] = ' 1457';
item["issue_id"] = '123420';
item["activity_id"] = '71';
item["comments"] = 'Testing';

array.push(item) // pushing the object in the declared array 
var strArray =JSON.stringify(array);// stringify the array 

//常规的api调用 获取('https:www.yourapi.com',{ 方法:'POST', 标题:{ '接受':'应用程序/json', '内容类型':'应用程序/json', }, 正文:JSON.stringify(strArray) })