Goal:
Use json_encode to format array data into a specified format
This is the needed format for the data after running through PHP json_encode:
NEEDED FORMAT
{
"top_level_data": [
{
"extension": {},
"sub_level_data1": 0
}
]
}
When I use this PHP:
$data = array('top_level_data' => array('extension' => array(),
'sub_level_data1' => 0
)
)
$data = json_encode($data);
I get this incorrect Output:
{
"top_level_data":{
"extension":[],
"sub_level_data1": 0
}
}
Question:
How can I modify my php to include the {} and the [] in the correct places as the Needed Format?
It's not clear how you're generating $data; if it's by the assignment you show then you can just add an extra layer of array at top_level_data, and cast the extension value to an object:
$data = array('top_level_data' => array(
array('extension' => (object)array(),
'sub_level_data1' => 0
)
)
);
If however you get the $data from another source, you can modify it like this:
$data['top_level_data']['extension'] = (object)$data['top_level_data']['extension'];
$data['top_level_data'] = array($data['top_level_data']);
Both methods yield this JSON:
{
"top_level_data": [
{
"extension": {},
"sub_level_data1": 0
}
]
}
Demo on 3v4l.org
json_encode will encode sequence array with []. The sequence array should has index from 0 to n. For other array, associative array and object will encoded with {}. Use the JSON_FORCE_OBJECT parameter of json_encode all the array will be encoded with {}.
Example:
echo json_encode(range(1,3)); // [1,2,3]
echo json_encode(array(2=>2)); // {"2":2}
echo json_encode(range(1,3),JSON_FORCE_OBJECT); // {"0":1,"1":2,"2":3}
echo json_encode((object)range(1,3)); // {"0":1,"1":2,"2":3}
Related
I am trying to create the payload/data using an PHP array as input, by using [json_encode]. I noticed that the results of payload_1 has squared brackets but that payload_2 does not.
Question:
How can I create payload_2 with the result of squared brackets in the same position as in payload_1 ? To clarify, the outcome of payload_2 should be same as outcome of payload_1.
<?php
// Create payload from string.
$payload_1 = "{
\"prenumeration\":
[
{
\"url\":\"http://www.google.com\"
}
]
}";
var_dump($payload_1);
echo "\n\n";
// Create payload from array.
$payload_2 = array(
"prenumeration" => array(
"url" => "http://www.google.com"
)
);
$payload_2 = json_encode($payload_2);
var_dump($payload_2);
echo "\n\n";
Results:
Result (payload_1):
"{"prenumeration":[{"url":"http://www.google.com"}]}"
Result (payload_2):
"{"prenumeration":{"url":"http:\/\/www.google.com"}}"
Try the following:
$payload_2 = array(
"prenumeration" => array(array(
"url" => "http://www.google.com"
))
);
prenumeration must be an array of associative arrays.
array("url" => "http://www.google.com") is an associative array of one element. Associative arrays are represented with curly brackets.
array(array("url" => "http://www.google.com")) is an array of one element (that happens to be an associative array). Arrays are represented with square brackets.
I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.
I'm trying to make my json output in the following format below, but I do not know how to code it to make it display in just format... I just have the values, any kind of help I can get on this is greatly appreciated!
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
},
{
"firstcolumn":"56036",
"loc":"Deli",
"lastA":"Activity",
"mTime":"2011-02-01 11:59:26.243",
"nTime":"2011-02-01 10:57:02.0",
"Time":"2011-02-01 10:57:02.0",
"Age":"9867 Hour(s)",
"ction":" ",
"nTime":null
}
You can use a PHP associative array to set the key => value's of your array to be converted to json. As you would expect the key of the php associative array becomes the key of the JSON object, and the same with the values.
$array = array(
'firstcolumn' => '56036',
"loc" => "Deli",
"lastA" => "Activity",
"mTime" => "2011-02-01 11:59:26.243",
"nTime" => "2011-02-01 10:57:02.0",
"Time" => "2011-02-01 10:57:02.0",
"Age" => "9867 Hour(s)",
"ction" => "",
"nTime" => NULL
);
You can do both arrays like this (using previous array to show concept but can replace with that same array())
$array2 = $array1;
$array2['firstcolumn'] = "56037";
$botharrays = array($array, $array2);
What we just did is put both sub arrays into one containing array so that when you encode the json it has each object separately.
array( array1, array2 )
Then use json_encode() to encode the array into the json format you requested
$JSON= json_encode($array);
or
$json = json_encode($botharrays);
I think you are looking for this:
$json = json_encode($myArray);
print_r($json);
I have a PHP data structure I want to JSON encode. It can contain a number of empty arrays, some of which need to be encoded as arrays and some of which need to be encoded as objects.
For instance, lets say I have this data structure:
$foo = array(
"bar1" => array(), // Should be encoded as an object
"bar2" => array() // Should be encoded as an array
);
I would like to encode this into:
{
"bar1": {},
"bar2": []
}
But if I use json_encode($foo, JSON_FORCE_OBJECT) I will get objects as:
{
"bar1": {},
"bar2": {}
}
And if I use json_encode($foo) I will get arrays as:
{
"bar1": [],
"bar2": []
}
Is there any way to encode the data (or define the arrays) so I get mixed arrays and objects?
Create bar1 as a new stdClass() object. That will be the only way for json_encode() to distinguish it. It can be done by calling new stdClass(), or casting it with (object)array()
$foo = array(
"bar1" => new stdClass(), // Should be encoded as an object
"bar2" => array() // Should be encoded as an array
);
echo json_encode($foo);
// {"bar1":{}, "bar2":[]}
OR by typecasting:
$foo = array(
"bar1" => (object)array(), // Should be encoded as an object
"bar2" => array() // Should be encoded as an array
);
echo json_encode($foo);
// {"bar1":{}, "bar2":[]}
Same answer, for PHP5.4+.
$foo = [
"bar1" => (object)["",""],
"bar2" => ["",""]
];
echo json_encode($foo);
Another simple examples, with something important to notice:
$icons = (object)["rain"=>["💧"], "sun"=>["🌞"], "lightrain"=>["🌦"]];
echo $icons->sun;
// 🌞
$icons = (object)["rain"=>"💧", "sun"=>"🌞", "lightrain"=>"🌦"];
echo $icons->sun;
// 🌞
There answer is no. There is no way for the function to guess your intent as to which array should be array and which should be objects. You should simply cast the arrays you want as object before json_encoding them
I'm trying to encode a two-dimensional PHP array to JSON with json_encode() and I'm having a problem:
My array looks like this:
$array = array( array( 1325368800, 6898 ) );
When I encode it to JSON using json_encode(), the output looks like this:
'data' : [
'0' : [ '0' : '1325368800', '1' : '6898' ]
]
I would like to get rid of the automatically generated integer keys and have it like this:
'data': [ [ '1325368800', '6898' ] ]
Any tips?
This can only happen if you give the JSON_FORCE_OBJECT flag to json_encode (live demo):
echo json_encode(array(array( 123, 123 )));
// outputs [[123,123]]
echo json_encode(array(array( 123, 123 )), JSON_FORCE_OBJECT);
// outputs {"0":{"0":123,"1":123}}
Make sure the second argument of json_encode is not set, or set to a value generated by ORing JSON_* constants together.
If, however, the data is an associative array, you can use array_values to get a JSON array instead of a JSON object:
$assocData = array('0' => array('0' => 123, '1'=>123));
$arrayData = array_map('array_values', array_values($assocData));
echo json_encode($arrayData);
By the way, the JSON output you cited is invalid, since it uses square brackets ([]) for objects, and misses a quote after "0.