superphonic
superphonic

Reputation: 8074

Convert array to particular JSON format

I am kicking my self for having to ask this question, but I cannot figure out how to convert the following array to the JSON format below. Simply json_encoding the array does not produce the square brackets needed.

PHP Array

$json = array(
              "api_key" => $api_key,
              "data"    => array(
                                "item" => array (
                                                "value" => rand(0, 5684),
                                                "text" => "Total"
                                                )
                                )
             );

JSON format required

{
    "api_key": "api key",
    "data": {
        "item": [
            {
                "value": 3212,
                "text": "Total"
            }
        ]
    }
}

How should I change the array to make json_encode produce the correct format, or is there some switch I am missing on the encoding?

Upvotes: 0

Views: 45

Answers (2)

lafor
lafor

Reputation: 12776

If you want item to be a list of dictionaries, you need an array of associative arrays in the input:

$json = array(
   "api_key" => 'foo',
   "data"    => array(
      "item" => array(
         array (
            "value" => rand(0, 5684),
            "text" => "Total"
         )
      )
   )
);

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075427

You're just missing out a level. In your PHP, item is an associative array with the value and text properties. But in the expected JSON, it's an array containing an object with value and text properties. So in your PHP structure, you need a simple array that you put your associative array in.

E.g.:

$json = array(
  "api_key" => $api_key,
  "data" => array(
    "item" => array( // <== The simple array
      array(         // <== Your original associative array
        "value" => rand(0, 5684) ,
        "text" => "Total"
      )
    )
  )
);

If you json_encode that, you get:

{
    "api_key": "your key",
    "data": {
        "item": [
            {
                "value": 605,
                "text": "Total"
            }
        ]
    }
}

Upvotes: 1

Related Questions