如何遍历Stripe集合JSON

时间:2017-11-22 15:35:00

标签: javascript angularjs json stripe-payments

我正在使用Stripe付款将一张发票清单返回给我的AngularJS应用。

我得到以下结果:

Stripe\Collection JSON: {
"object": "list",
"data": [
    {
        "id": "in_1BKR1lK9EsaSH2dAtMQ4JF1K",
        "object": "invoice",
        "amount_due": 113,
        "application_fee": null,
        "attempt_count": 1,
        "attempted": true,
        "billing": "charge_automatically",
        "charge": "ch_1BKRxsK9EsaSH2dA0xW34Qsr",
        "closed": true,
        "currency": "gbp",
        "customer": "cus_9ry4RT082N7T7N",
        "date": 1509799533,
        "description": null,
        "discount": null,
        "ending_balance": 0,
        "forgiven": false,
        "lines": {
            "object": "list",
            "data": [
                {
                    "id": "ii_1BJm2pK9EsaSH2dA6t4ytmm6",
                    "object": "line_item",
                    "amount": 6,
                    "currency": "gbp",
                    "description": "Remaining time on per act monthly after 02 Nov 2017", 

...等

如何遍历此JSON以列出每个发票对象?

我试过了:

$scope.myUserData.invoices = result.data; (returns above JSON) 
$scope.myUserData.invoices = result.data[0]; (returns "S")
$scope.myUserData.invoices = result.data.object; (returns blank)
$scope.myUserData.invoices = result.data.data; (returns blank)

3 个答案:

答案 0 :(得分:3)

由于您的result.data[0]返回字符'S',因此您的result对象很可能是字符串。因此,您可以尝试使用JSON.parse(),如下所示:

var json = JSON.parse(result);
console.log(json.data[0]);

编辑:使用OP的观察结果进行调整

你的结果对象在路上的某个地方是字符串化的(首先应该是一个json对象),然后使用

$scope.myUserData.invoices = angular.fromJson(result.data);

应该有用。

答案 1 :(得分:0)

也许会有所帮助



let x = 'Stripe\Collection JSON: {hello:"world"}';//Should be your result instead this string
x = x.replace("Stripe\Collection JSON: ", "");
x = JSON.stringify(x)
x = JSON.parse(x);
console.log(x)




只需输入您的结果值即可。然后你应该有一个JSON对象,并执行这个result.data [0]

答案 2 :(得分:-1)

爱德华(Edward)给出的答案稍有变化,反斜杠需要转义。

这使我可以仅使用Typescript获得结果,也可以在Angular中使用

  let x = result._body;
  x = x.replace("Stripe\\Collection JSON: ", "");
  x = JSON.parse(x);

  x.data.forEach(element => {
    console.log('card JSON: ' + JSON.stringify(element));
    console.log('card id: ' + element.id);
  });