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
Solved

JSON Array inside an array

Posted on 2013-05-20
10
331 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
  • 4
  • 4
  • 2
10 Comments
 
LVL 109

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 109

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
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.

 
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 34

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 109

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 34

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 34

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 109

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 34

Expert Comment

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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses four methods for overlaying images in a container on a web page
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…
The viewer will learn how to count occurrences of each item in an array.

829 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