Solved

JSON Array inside an array

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

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
$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 108

Expert Comment

by:Ray Paseur
Comment Utility
@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
 
LVL 10

Expert Comment

by:ienaxxx
Comment Utility
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
Comment Utility
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
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
Comment Utility
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 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
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
Comment Utility
Strange choice for the answer. I would have expected 39180990.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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.

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now