构建JSON编码对象

时间:2017-05-24 06:35:12

标签: php arrays json string

我正在向API提交数据。它想要这样的格式:

{
  "subscribers": [{
    "email": "john@acme.com",
    "time_zone": "America/Los_Angeles",
    "custom_fields": {
      "name": "John Doe"
    }
  }]
}

我正在PHP中构建JSON对象:

$subscriberInfo = [
    'subscribers' => [
        ['email' => $email],
        ['custom_fields'] => [
            ['name' => "Bob"]
        ]
    ]   
];
$encoded = json_encode($subscriberInfo);

API拒绝['custom_fields']

我做错了什么?

5 个答案:

答案 0 :(得分:2)

更正数组格式。您使用的是错误的数组格式。

Try this snippet here

class StaffUser(User):
    parent = models.ForeignKey(
        'users.User',
        on_delete=models.CASCADE,
        related_name='staff_childs',
        null=True
    )

答案 1 :(得分:1)

试试这个,检查 live demo

<div style="height:500px">
  <div class="searchfixed">My Button Search</div>
</div>

答案 2 :(得分:1)

试试这个例子:

<?php
$subscriberEx = array(
    'subscribers' => array(
        array('email' => "s",
        'custom_fields'=>
            array('name' => "Bob")
        )
    )
);
$subscriber_encoded = json_encode($subscriberEx);
echo $subscriber_encoded;
?>

<强>输出:

{  
   "subscribers":[  
      {  
         "email":"s",
         "custom_fields":{  
            "name":"Bob"
         }
      }
   ]
}

答案 3 :(得分:0)

API也应拒绝“电子邮件”字段。

应该是;

PriorityQueue

答案 4 :(得分:0)

你的偏移是完全错误的。你不应该有&#34; [&#34;在&#39; custom_field&#39;之后的对象的第4行:

$subscriberInfo = [
    'subscribers' => [
        ['email' => $email],
        ['custom_fields' =>
            ['name' => "Bob"]
        ]
    ]   
];
$encoded = json_encode($subscriberInfo);

...返回:

"subscribers":[{"email":""},{"custom_fields":{"name":"Bob"}}]}