PHP json_encode - JSON_FORCE_OBJECT mixed object and array output - php

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

Related

How to use PHP json_encode to format array data with []

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}

how do I get my php array to json

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);

json_decode returns string type instead of object

I'm passing a JSON-encoded string to json_decode() and am expecting its output to be an object type, but am getting a string type instead. How can I return an object?
In the docs, the following returns an object:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
However, if I json_encode() the string first and then call json_decode(), the output is a string and not an object:
$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));
This is just a simplified example. In practice what I'm doing is pushing a JSON-encoded string to PHP via AJAX. However it does illustrate the problem of converting this encoded JSON string to an object I can read in PHP, e.g., "$json->a".
How can I return an object type?
thanks for the replies !
The actual context for this question was am using a JSON Response from a API.
But when I do the json_decode to this response and try to access the values like - $json=json_decode(json response from API);
echo $json->a
it gives me a error: Object of class stdClass could not be converted to string
The function json_encode is used to encode a native PHP object or array in JSON format.
For example, $json = json_encode($arr) where $arr is
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
);
would return the string $json = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'. At this point, you do not need to encode it again with json_encode!
To obtain your array back, simply do json_decode($json, true).
If you omit the true from the call to json_decode you'll obtain an instance of stdClass instead, with the various properties specified in the JSON string.
For more references, see:
http://www.php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.json-decode.php
var_dump(json_decode($json, true));
http://hk.php.net/manual/en/function.json-decode.php
Instead of writing on the JSON array, try putting it into a PHP array first.
<?php
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5
);
//Then json_encode()
$json = json_encode($array);
echo $json;
die;
?>
In you case, you are using ajax. So when you get a success, you can do this:
$.ajax({
url: 'example.com',
data: {
},
success: function(data) {
console.log(data);
}
});
Where after data inside console.log() can add the json var like data.a, data.b...
Also, with the string you providedm you do not need to json_encode since it is alrady in json format
in your question you confused json_encode with and json_decode:
$json = json_encode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_decode($json));
its should be:
$json = json_decode('{"a":1,"b":2,"c":3,"d":4,"e":5}');
var_dump(json_encode($json));

push array into multidimensional array?

I have json_encoded array that i would like to add to using php
[{"id":"a","value":"2"},{"id":"b","value":"2"}]
I want to add the following to the array above:
array("id" => c, "value" => "3")
I tried json_decode then trying to push the array into that but im confused on how to do that
Make sure you use json_decode in array mode rather than object mode:
// Default: JSON is decoded as object
$json_object = json_decode($json_string);
// Pass true in the second argument to get an array instead
$json_array = json_decode($json_string, true);
// Push a new entry onto the end
$json_array[] = array("id" => c, "value" => "3");
// Re-encode JSON string, if needed
$json_final_string = json_encode($json_array);

Generate json string from multidimensional array data [duplicate]

This question already has answers here:
How to create an array for JSON using PHP?
(8 answers)
Closed 1 year ago.
I am using a plugin that requires an array of associative rows as a json formatted string -- something like:
[
{oV: 'myfirstvalue', oT: 'myfirsttext'},
{oV: 'mysecondvalue', oT: 'mysecondtext'}
]
How do I convert my multidimensional array to valid JSON output using PHP?
Once you have your PHP data, you can use the json_encode function; it's bundled with PHP since PHP 5.2.
In your case, your JSON string represents:
a list containing 2 elements
each one being an object, containing 2 properties/values
In PHP, this would create the structure you are representing:
$data = array(
(object)array(
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext',
),
(object)array(
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext',
),
);
var_dump($data);
The var_dump gets you:
array
0 =>
object(stdClass)[1]
public 'oV' => string 'myfirstvalue' (length=12)
public 'oT' => string 'myfirsttext' (length=11)
1 =>
object(stdClass)[2]
public 'oV' => string 'mysecondvalue' (length=13)
public 'oT' => string 'mysecondtext' (length=12)
And, encoding it to JSON:
$json = json_encode($data);
echo $json;
You get:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
By the way, from what I remember, I'd say your JSON string is not valid-JSON data: there should be double-quotes around the string, including the names of the objects' properties.
See http://www.json.org/ for the grammar.
The simplest way would probably be to start with an associative array of the pairs you want:
$data = array("myfirstvalue" => "myfirsttext", "mysecondvalue" => "mysecondtext");
then use a foreach and some string concatenation:
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{oV: '".addslashes($key)."', oT: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]";
Or if you have a recent version of PHP, you can use the json encoding functions built in - just be careful what data you pass them to make it match the expected format.
This is one of the most fundamental rules in php development:
DO NOT MANUALLY BUILD A JSON STRING.
USE json_decode().
If you need to populate your data in a loop, then gather all of your data first, then call json_encode() just once.
Do not try to wrap/prepend/append additional data to an encoded json string. If you want to add data to the json payload, then decode it, add the data, then re-encode it.
It makes no difference if you pass object type or array type data to json_encode() -- by default, it will still create a string using square braces for indexed arrays and curly braces for iterable data with non-indexed keys.
Code:
$array = [
[
'oV' => 'myfirstvalue',
'oT' => 'myfirsttext'
],
[
'oV' => 'mysecondvalue',
'oT' => 'mysecondtext'
]
];
echo json_encode($array);
Output:
[{"oV":"myfirstvalue","oT":"myfirsttext"},{"oV":"mysecondvalue","oT":"mysecondtext"}]
For clarity, I should express that the OP's desired output is not valid json because the nested keys are not double quote wrapped.
You can use the stdClass, add the properties and json_encode the object.
$object = new stdClass();
$object->first_property = 1;
$object->second_property = 2;
echo '<pre>';var_dump( json_encode($object) , $object );die;
Voilà!
string(40) "{"first_property":1,"second_property":2}"
object(stdClass)#43 (2) {
["first_property"]=>
int(1)
["second_property"]=>
int(2)
}
This is the php code to generate json format.
while ($row=mysqli_fetch_assoc($result))
{
$array[] = $row;
}
echo '{"ProductsData":'.json_encode($array).'}'; //Here ProductsData is just a simple String u can write anything instead

Categories