Solved

JSON Array inside an array

Posted on 2013-05-20
10
344 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

Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

Question has a verified solution.

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

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it i…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

729 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