Paul Dessert
Paul Dessert

Reputation: 6389

Building a JSON encoded object

I'm submitting data to an API. It wants the format like this:

{
  "subscribers": [{
    "email": "[email protected]",
    "time_zone": "America/Los_Angeles",
    "custom_fields": {
      "name": "John Doe"
    }
  }]
}

I'm building the JSON object in PHP like this:

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

The API is rejecting ['custom_fields'].

What am I doing wrong?

Upvotes: 0

Views: 48

Answers (5)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Correct array format. You are using wrong array format.

Try this snippet here

$subscriberInfo = array(
    'subscribers' => array(
        array(
          'email' => "s",
          'custom_fields'=>
             array('name' => "Bob")
        )
    )
);

Upvotes: 1

RaMeSh
RaMeSh

Reputation: 3424

Try this example:

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

Output:

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

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

Try this, check the live demo

$subscriberInfo = [
    'subscribers' => [[
        'email' => $email,
        'custom_fields' => 
            ['name' => "Bob"]
        ]
    ]   
];

Upvotes: 0

Mikah J. Trent
Mikah J. Trent

Reputation: 1

Your offset is simply incorrect. You should not have the "[" on line 4 of your object, after 'custom_field':

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

... returns:

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

Upvotes: 0

Memduh
Memduh

Reputation: 866

API should be rejecting 'email' field also.

It should be;

$subscriberInfo = [
    'subscribers' => [
        [
            'email' => $email,
            'custom_fields' => [
                'name' => "Bob"
            ]
        ]
    ]   
];

$encoded = json_encode($subscriberInfo);

Upvotes: 0

Related Questions