This question already has answers here:
Pretty-Printing JSON with PHP
(27 answers)
Closed 3 years ago.
I've seen multiple answers in here but none of them had a solution to my question, so I made an account to ask this question. I understand now that \n is not an allowed character in json because the backslash is not allowed and that's why the problem is occurring.
I have the following code to encode an array in json:
<?php
$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
echo json_encode($data);
I'm trying to have the string outputted as follows:
{
"test1": "something1",
"test2": "something2",
"test3": "something3"
}
But what I'm getting is this:
{"test1":"something1","test2":"something2","test3":"something3"}
This is my go at it:
<?php
$data = array('test1' => 'something1\n', 'test2' => 'something2\n', 'test3' => 'something3\n');
echo json_encode($data);
but this returns
{"test1":"something1\n","test2":"something2\n","test3":"something3\n"}
You can add a second parameter to json_encode. This is called the JSON_PRETTY_PRINT constant:
<?php
$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
echo json_encode($data, JSON_PRETTY_PRINT);
You can use JSON_PRETTY_PRINT with header
$data = array('test1' => 'something1', 'test2' => 'something2', 'test3' => 'something3');
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data,JSON_PRETTY_PRINT);
OR
$json= json_encode($data,JSON_PRETTY_PRINT);
printf("<pre>%s</pre>", $json);
JSON is an interchange format, so you need not to be concerned about the looks very much.
Anyway, you can use flag constants to alter the encoding process
<?php
$a = '{"test1":"something1","test2":"something2","test3":"something3"}';
print_r(json_encode(json_decode($a, true), JSON_PRETTY_PRINT));
See live example: https://3v4l.org/CEc3L
Related
This question already has answers here:
Pretty-Printing JSON with PHP
(27 answers)
Closed 1 year ago.
Hi I have php code which I use json_encode to create from an array a json code, the thing or porblem is that json_encode becomes the array to a lineal json what I mean it this:
$data["auth"]["cert"] = ["-----BEGIN CERTIFICATE-----\nMIIGjjCCBXagAwIBAgIDAR4jMA0GCSqGSIb3DQEBCwUAMIGmMQswCQYDVQQGEwJD\nTDEYMBYGA1UEChMPQWNlcHRhLmNvbSBTLkEuMUgwRgYDVQQDEz9BY2VwdGEuY29t\nIEF1dG9y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1tSDG4RopV8tk/PH\nbtK1Fk0Qu7NliHr+PKb9w69wiw8BZ7dDU+igqJrywXl+Tnm8CvpbOAL8qQZqMzXM\nGvGBelWSq2HzxrIURD4X1yqzPvRKCTEbAPn4cgnmUBIpOtkdDJjrwuMD8dIT6J4y\nqmlpYZEWYwMCgYAEw4awwejzUbpNN+sdPygdTADYo5u1Nsyt54sA6fJ+OzgY1Gpj\nCtf1M5PkI3J+oDKjuchiqat926H4DzOSLzMmrNlJVtdiv+umQM4mDL/PL9AJsgak\nIWXvYVvhb7QLwm85obG46XlmW7mJwbSVQkmdgD9ZFGrIaM/k/36h8MoI8QKBgD8R\nChjmUTkTq+vXCacpW+0+21R76j4VaJrmey+MtDYkelVEf3lPtf7lr86pvDm7FDtq\nL74nIB0Cc545EXPmNx+IyYzfspu5UbwplbEH0IqOP84tGNnKRx9bq4oHGk2wENHH\nc/feGzdrVPgkQ6CVGFWQV39MJDoGDVgYrz7d3t3bAoGBAK+UnIFrRJ225UMsIM5Ao2\nryKtwPemdHypIVK3WOV1yRpa5aBqemrTQkijbLx8lVxoeID8Lw4zHybK6V9mAHsf\nRhfHsmBz3f4mYoKVoyVDelxpx+IGkGibvzNQB5BFWuu8kZeDPkhcPbk4pHFUf/jm\nCvLdtcSmumV5hxnVdtwjdlQD\n-----END PRIVATE KEY-----"];
$data["emisor"] = "76063822-6";
$data["resolucion"] = ["fecha" => "2014-06-17", "numero" => 57];
$data["secuencia"] = 1;
$data["documentos"][] = [
"TpoDoc" => 39,
"NroDoc" => 3,
"TasaImp" => 0,
"FchDoc" => "2021-07-05",
"MntExe" => 100,
"MntNeto" => 0,
"MntIVA" => 0,
"MntTotal" => 100
];
$data = json_encode($data);
That array becomes to this:
{"auth":{"cert":{"cert-data":"-----BEGIN CERTIFICATE-----\nMIIGjjCCBXagAwIBAgIDAR4jMA0GCSqGSIb3DQEBCwUAMIGmMQswCQYDVQQGEwJD\nTDEYMBYGA1UEChMPQWNlcHRhLmNvbSBTLkEuMUg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Gh17cjb/vP1s8CgYEAsJguDDB0uNC/oCEi1tSDG4RopV8tk/PH\nbtK1Fk0Qu7NliHr+PKb9w69wiw8BZ7dDU+igqJrywXl+Tnm8CvpbOAL8qQZqMzXM\nGvGBelWSq2HzxrIURD422X1yqzPvRKCTEbAPn4cgnmUBIpOtkdDJjrwuMD8dIT6J4y\nqmlpYZEWYwMCgYAEw4awwejzUbpNN+sdPygdTADYo5u1Nsyt54sA6fJ+OzgY1Gpj\nCtf1M5PkI3J+oDKjuchiqat926H4DzOSLzMmrNlJVtdiv+umQM4mDL/PL9AJsgak\nIWXvYVvhb7QLwm85obG46XlmW7mJwbSVQkmdgD9ZFGrIaM/k/36h8MoI8QKBgD8R\nChjmUTkTq+vXCacpW+0+21R76j4VaJrmey+MtDYkelVEf3lPtf7lr86pvDm7FDtq\nL74nIB0Cc545EXPmNx+IyYzfspu5UbwplbEH0IqOP84tGNnKRx9bq4oHGk2wENHH\nc/feGzdrVPgkQ6CVGFWQV39MJDoGDVgYrz7d3t3bAoGBAK+UnIFrRJ5UMsIM5Ao2\nryKtwPemdHypIVK3WOV1yRpa5aBqemrTQkijbLx8lVxoeID8Lw4zHybK6V9mAHsf\nRhfHsmBz3f4mYoKVoyVDelxpx+IGkGibvzNQB5BFWuu8kZeDPkhcPbk4pHFUf/jm\nCvLdtcSmumV5hxnVdtwjdlQD\n-----END PRIVATE KEY-----"}},"emisor":"76063822-6","resolucion":{"fecha":"2014-06-17","numero":57},"secuencia":1,"documentos":[{"TpoDoc":39,"NroDoc":3,"TasaImp":0,"FchDoc":"2021-07-05","MntExe":100,"MntNeto":0,"MntIVA":0,"MntTotal":100}]}
I mean in a json of one line BUT I need this kind of json:
{
"auth":{
"cert":{
"cert-data":"-",
"pkey-data":""
}
},
"emisor":"76063822-6",
"resolucion":{
"fecha":"2014-06-17",
"numero":57
},
"secuencia":1,
"documentos":[
{
"TpoDoc":39,
"NroDoc":3,
"TasaImp":0,
"FchDoc":"2021-07-05",
"MntExe":100,
"MntNeto":0,
"MntIVA":0,
"MntTotal":100
}
]
}
How you can see this json is not in one line I wonder how can I transform that lineal json to this kind of json if I am using json_encode?
Thanks
Just format it this way:
$data = json_encode($data, JSON_PRETTY_PRINT);
More info: https://www.php.net/manual/en/function.json-encode.php
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
This question already has answers here:
print an array as code
(4 answers)
Closed 2 years ago.
for very special purpose I need to transform PHP array into PHP code. I will try to explain what I mean in code below:
$a = array('a' => 'abc', 'path' => INCLUDE_DIR.'/file.txt', 'number' => 1234);
$php_code = some_magic_function($a);
echo $php_code; // outputs: "array('a' => 'abc', 'path' => '/path/to/file.txt', 'number' => 1234)"
So it would write back array as PHP code. I can not find any library that would help me with this.
Any ideas or hints ? Thanks in advance.
I think you want to print the array as a string, in the exact format it would be written in your code.
If so, then the var_export() function is what you need, e.g. something like this:
$a = array('a' => 'abc', 'path' => '/file.txt', 'number' => 1234);
$str = var_export($a, true);
echo $str;
Demo: http://sandbox.onlinephpfunctions.com/code/0b1da8fc0199a34539a55313680e982f9fddd14f
This question already has answers here:
Help editing JSON to make an array rather than a 'dictionary'
(2 answers)
Closed 9 years ago.
I am having arrays from my PHP
{"lista":[{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Novi_Sad"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Kragujevac"},{"Grad":"Beograd"},{"Grad":"Kragujevac"},{"Grad":"Beograd"}]}
and when I use:
$arr = array_flip(array_map('serialize', $rows));
$lista = array_map('unserialize', array_flip($arr));
echo json_encode((object) array('lista' => $lista));
I am getting
{"lista":{"19":{"Grad":"Beograd"},"18":{"Grad":"Novi_Sad"},"20":{"Grad":"Kragujevac"}}}
Question is how can I remove this numbers that are in front of my arrays?
Try changing
echo json_encode((object) array('lista' => $lista));
to
echo json_encode((object) array('lista' => array_values($lista)));
Note : not tested
I think you need to populate the array as in the example in the documentation in the php manual:
http://php.net/manual/en/function.json-encode.php
From PHP Site:
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
apply array_values before encoding into Json_encode
$lista = array_values(array_map('unserialize', array_flip($arr)));
echo json_encode((object) array('lista' => $lista));
I would like to know how can we make the JSON based array using json_encode() PHP ;
The format of the array should be look like this.
callback([{"ProductID":1,"ProductName":"Chai","UnitPrice":18,"UnitsInStock":39,"Discontinued":false}])
When we need the this header("Content-type: application/json");
UPDATE
in above format you can see the format check the numeric values, json_encode not mention the double quotes the numeric values. I just want to configure the Mysql values on this format, like numeric value without double quotes, and string values with double quotes. We should have to configure mysql values on this format.
Thanks
edit: It appears you are trying to serve JSONP, not JSON. JSONP should be given the content type of application/javascript like this:
header("Content-type: application/javascript");
$json = json_encode(
array(
array(
"ProductID" => 1,
"ProductName" => "Chai",
"UnitPrice" => 18,
"UnitsInStock" => 39,
"Discontinued" => false
)
)
);
echo "callback({$json})";
Example:
$array = array(
'ProductID' => 1,
'ProductName' => 'Chai',
'UnitPrice' => 18,
'UnitsInStock' => 39,
'Discontinued' => false
);
header("Content-type: application/json");
echo json_encode($array);
http://us.php.net/manual/en/function.json-encode.php
the example on that page should tell you everything you need to know.