0

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?

2 Answers 2

1

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"
            }
        ]
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Clearly I'm done for the day :-/ Thanks for not ripping me a new one for being so dense.
@superphonic: It's pretty easy not to see the odd [ and ] here and there. :-)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.