Prevent json_encode() from automatically generating integer keys - php

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.

Related

post string and array using curl [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

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}

Create payload from array

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.

How can I force PHP's json_encode integer values to be encoded as String?

I'm using PHP v5.6.
As i read that php json_encode function is automatically converting int to string. But not in my case. Json_encode is still return it to int not string.
Like example:
json_encode(['code' => 200, 'results' => [id=> 1]]);
my expected results is all become a string. but what i get is
{"code":200,"results":{"id": 1}}
Expected output:
{"code":"200","results":{"id": "1"}}
How can i change all the result become string without using "" for every value?.
NB: results array is based on query.
In the link posted by Thomas in comments, one user suggests that you do this:
$data = json_encode(array_map('strval', $data));
This might not be the most efficient in terms of performace though, since every entry on the array will pass through the strval function.
json_encode(['code' => 200, 'results' => [id=> strval(1)]]);
With strval() php will return
The string value of var.
To ensure that all numeric "leaf nodes" of a potentially multi-dimensional array are cast as strings, call array_walk_recursive() and make conditional changes to each value type. By checking if the value "is numeric", you prevent values like null and booleans from being cast as strings.
Code: (Demo)
$array = [
'code' => 200,
'results' => [
'id' => 1
],
'a' => [
[
'b' => [
4,
null,
false
]
]
]
];
array_walk_recursive(
$array,
function(&$v) {
if (is_numeric($v)) {
$v = strval($v);
}
}
);
echo json_encode($array);
Output:
{"code":"200","results":{"id":"1"},"a":[{"b":["4",null,false]}]}

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