简体   繁体   中英

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?

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 .

Eg:

$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"
            }
        ]
    }
}

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"
         )
      )
   )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM