Solved

JSON Array inside an array

Posted on 2013-05-20
10
341 Views
Last Modified: 2013-06-04
Im trying to put some data in, for json_decode, but I want an array inside an array. The inner array I dont have any names for, its just a list, so I thought the following would work:-
{
"type" : "combo",
"attribute" : "LIST",
"Values" : {"Male","Female"} 
}

Open in new window


However it doesnt seem to decode anything when I try it with:-
$strJSONTest = '{"type" : "combo", "attribute" : "LIST", "Values" : {"Male","Female"} }';
$jsonArr = json_decode($strJSONTest);
print_r $jsonArr['type'];

Open in new window


I know its the inner array, as the following code works:-
$strJSONTest = '{"type" : "combo", "attribute" : "LIST", "Values" : "Test" }';
$jsonArr = json_decode($strJSONTest);
print_r $jsonArr['type'];

Open in new window

0
Comment
Question by:tonelm54
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
10 Comments
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39180927
http://www.json.org/
Why not create the data structure you want, and then use JSON_Encode() to create the JSON string?  Easy!

Keep in mind, however, that JSON will decode a JSON String into an object with UTF-8 encoding.  That is just how it works.  So even if you start with an outer array you will get an object back from the process.  Inner arrays are preserved.
http://www.laprbass.com/RAY_temp_tonelm54.php

<?php // RAY_temp_tonelm54.php
error_reporting(E_ALL);

$jso = <<<EOD
{
"type" : "combo",
"attribute" : "LIST",
"Values" : {"Male","Female"}
}
EOD;

// CREATE THE TEST DATA
$dat = array
( 'type'      => 'combo'
, 'attribute' => 'LIST'
, 'Values'    => array( 'Male', 'Female' )
)
;

// ENCODE INTO A JSON STRING FOR TRANSPORT
$jso = json_encode($dat);

// DECODE THE STRING INTO AN OBJECT
$obj = json_decode($jso);

// WHAT IS IN THE ORIGINAL AND THE OBJECT?
var_dump($dat);
var_dump($obj);

Open in new window

0
 
LVL 10

Expert Comment

by:ienaxxx
ID: 39180959
$strJSONTest = '{"type" : "combo", "attribute" : "LIST", "Values" : {"1": "Male", "2": "Female"} }';

This will fix it.
The matter is it can't analyze the json cause it's invalid.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39180990
@ienaxxx: It will create a valid JSON string, but it will not decode the inner structure Values into an array.  To get the array, you would need to use brackets instead of curly braces.

<?php // RAY_temp_ienaxxx.php
error_reporting(E_ALL);

$jso = <<<EOD
{
"type" : "combo",
"attribute" : "LIST",
"Values" : ["Male","Female"]
}
EOD;

// DECODE THE STRING INTO AN OBJECT
$obj = json_decode($jso);

// WHAT IS IN THE OBJECT?
var_dump($obj);

Open in new window

0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 10

Expert Comment

by:ienaxxx
ID: 39181006
I have this result:
stdClass Object ( [type] => combo [attribute] => LIST [Values] => stdClass Object ( [1] => Male [2] => Female ) )

Open in new window


and this if i use the boolean ASSOC as the second parameter. ( $jsonArr = json_decode($strJSONTest, true);   )

Array ( [type] => combo [attribute] => LIST [Values] => Array ( [1] => Male [2] => Female ) )

Open in new window



So i think you are wrong. :-)
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39181029
ienaxxx beat me to the punch. I always use the optional "true" parameter with json_decode so I get the original array back instead of an object.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39181045
Wrong, or at best, Lazy!  I find that the object-oriented notation is so much easier to write that I actively avoid using an array if I can use an object instead.  For every property I save a few keystrokes and eliminate the fiddly punctuation in the brackets and quotes.  I never even looked at the second parameter of JSON_Decode()!  Also, I have not tested the notation for transport so I don't know what it would do in JavaScript or another programming language.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39181115
The JSON results should be the same, no matter what method you use to encode/decode. If it's a plain array where keys aren't explicitly set, then encoding should produce the square-bracket notation that Ray mentioned: [ "X", "Y", "Z" ].

What ienaxxx produced was technically wrong, because it would change the keys (since array keys start at 0), but his formatting was technically correct:

...{"1": "Male", "2": "Female"} ...
Will produce:
[1] => Male
[2] => Female

[ "Male", "Female"]
Will produce:
[0] => Male
[1] => Female

...{"0": "Male", "1": "Female"} ...
Will produce:
[0] => Male
[1] => Female

So if you don't need to specify the keys/indexes, then use the square bracket notation for arrays. If you customize your keys, then use the { "Key" : "Value" } notation. The notation itself isn't "object-oriented" or "array-oriented". The only thing that turns a JSON string into an object or an array is the decoding step.
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39181132
Just to be extra-clear, the reason that decoding didn't work is because you tried to use { } brackets without specifying the keys.

{ } means that you are going to specify the contents in the format of:
"KeyA" : "ValueA", "KeyB" : "ValueB"

[ ] means that you are going to specify the contents in the format of:
"ValueA", "ValueB"
(and JSON decoding provides the keys)

So:
{"Male","Female"} is wrong

["Male","Female"] is right
{"0":"Male","1":"Female" } is also right
0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39181246
If you want an object with an embedded array, it seems to require some tinkering with the choice of curly braces vs square brackets.

<?php // RAY_temp_tonelm54.php
error_reporting(E_ALL);

$jso = <<<EOD
{
"type" : "combo",
"attribute" : "LIST",
"Values" : {"0":"Male","1":"Female" }
}
EOD;


// DECODE THE STRING
$obj = json_decode($jso);

// WHAT IS IN THE OBJECT?
var_dump($obj);

// DECODE THE STRING AGAIN
$arr = json_decode($jso, TRUE);

// WHAT IS IN THE ARRAY?
var_dump($arr);


$jso = <<<EOD
{
"type" : "combo",
"attribute" : "LIST",
"Values" : ["Male","Female"]
}
EOD;


// DECODE THE STRING
$obj = json_decode($jso);

// WHAT IS IN THE OBJECT?
var_dump($obj);

// DECODE THE STRING AGAIN
$arr = json_decode($jso, TRUE);

// WHAT IS IN THE ARRAY?
var_dump($arr);

Open in new window

Interesting!  Best to all, over and out, ~Ray
0
 
LVL 35

Expert Comment

by:gr8gonzo
ID: 39218926
Strange choice for the answer. I would have expected 39180990.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

732 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question