json from file to file in same style in oneline per line - php

i wanna convert a json file has text like this design json_text https://phponlines.com/result/e2j9RgRnm7
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
var_dump(json_encode($json_decoded));
then after i edit it to get same design again but i get different deisng instead in one line
[{"id":"1","name":"john","bd":[]},{"id":"2","name":"gary","bd":[1,2]}]
but what i want is
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]

As stated in my comments above, this is not particularly advisable, and writing any portion of a JSON file by hand is even more inadvisable.
But if you do not wish to see the light, then at least the use the minimal amount of darkness.
// polyfill for PHP<8.1
if (!function_exists('array_is_list')) {
function array_is_list(array $a) {
return $a === [] || (array_keys($a) === range(0, count($a) - 1));
}
}
function do_weird_json(array $input) {
if( ! array_is_list($input) ) {
throw new Exception('Input data must be a list');
}
return sprintf("[\n%s\n]\n", implode(",\n", array_map('json_encode', $input)));
}
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
$json_decoded[1]['name'] = 'bill';
var_dump(do_weird_json($json_decoded));
Output:
string(74) "[
{"id":"1","name":"john","bd":[]},
{"id":"2","name":"bill","bd":[1,2]}
]
"
Again, the best thing to do would be to leave the JSON as the default, not-human-friendly format and use a client-side tool like jq, etc to reformat the JSON for you for viewing purposes.

Related

Generate dynamic html with JSON output (with php)

I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

PHP convert JSON array to nested

I'm trying to get JSON by name and save it as a variable with everything related to that nest,
what would the best way to accomplish this?
(in my scenario the names are unique)
[{
"name": "Joe",
"age": "30",
"gender": "male"
},
{
"name": "Logan",
"age": "27",
"gender": "male"
}]
to something like this
{
"Joe": [{
"name": "Joe",
"age": "30",
"gender": "male"
}],
"Logan": [{
"name": "Logan",
"age": "27",
"gender": "male"
}]
}
i need to be able to search on the name to get the correct one, the API switches order so can't get it from just id
Hi This might helps you
$list = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}]';
$newjson = json_decode($list, true);
$final = [];
foreach ($newjson as $key => $value) {
$final[$value['name']][]=$value;
}
$finaloutput = json_encode($final, true);
echo "<pre>";
print_r($finaloutput);
echo "</pre>";
exit;
The output is
{"Joe":
[{"name":"Joe","age":"30","gender":"male"}],
"Logan":
[{"name":"Logan","age":"27","gender":"male"}]}
The Laravel Collections Library is a very useful lib to use cases like yours.
For this problem you could use the keyBy method!
$json = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}
]';
$array = collect(json_decode($json, true))->keyBy('name')->all();
print_r($array); // will be the array with the keys defined by the name!
See https://laravel.com/docs/5.5/collections#method-keyby

Get Json Object from external URL with PHP

I have an URL that returns the JSON object below:
{
"addressList": {
"addresses": [
{
"id": 0000000,
"receiverName": "Name Example",
"country": {
"id": "BRA",
"name": "Brasil"
},
"state": {
"id": "SP"
},
"city": "São Paulo",
"zipcode": "00000000",
"type": "Residential",
"street": "000, St Example",
"number": 00,
"neighborhood": "Example",
"hash": "1bf09357",
"defaultAddress": false,
"notReceiver": false
}
]
}
}
I want to get the state value, how can I retrieve that with PHP?
I tried, something like this, but I couldn't get the state value, that should be SP in this case.
$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';
$json_o = json_decode($string);
$estado = $json_o->state;
How can I achieve the result I want?
Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).
From then on, you can decode the value and access your data:
$json_o = json_decode($string);
$estado = $json_o->addressList->addresses[0]->state->id;
If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":
$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);
Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".
Your JSON has a couple of syntax errors:
"id": 0000000
"number": 00
JSON doesn't support leading zeros. If precise formatting is important, use strings:
"number": "00"
"id": "0000000"
Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.
Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:
$json_string ="..."; //your source, to be decoded
$json_o= json_decode($json_string);
if(is_null($json_o)): //there was an error decoding
$errno = json_last_error();
$err_msg = json_last_error_msg();
die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;
Try:
$json_o = json_decode($string, true);
$estado = $json_o['addressList']['addresses'][0]['state']['id'];

Error in JSON length returned by PHP count

This is the JSON response that I'm getting from database. I want to print these data. For now, there's only 2 entries in my table. So the length of JSON should be 2. As data increases, count has to get increase. SO for showing output, I use a for loop. And I used count() for limiting the iteration of loop only once through the JSON.
MY JSON:
{
"log": [
{
"action": "qq",
"id": "1",
"Time": "2014-05-19T15:40:06+05:30",
"user": {
"firstName": "dani",
"type": {
"zzs": "1",
"typename": "lolo",
"id": "1",
"zzt": "1",
"zzu": "1",
"zzv": "1",
"zzw": "1",
"zzx": "1"
},
"id": "1",
"lastName": "fed",
"password": "lmfao",
"userName": "fyi"
},
"userIpAddress": "101.15.23.45"
},
{
"action": "vv",
"id": "2",
"Time": "2014-05-20T10:16:33+05:30",
"user": {
"firstName": "dani",
"type": {
"zzs": "1",
"typename": "lolo",
"id": "1",
"zzt": "1",
"zzu": "1",
"zzv": "1",
"zzw": "1",
"zzx": "1"
},
"id": "1",
"lastName": "web",
"password": "rolf",
"userName": "asap"
},
"userIpAddress": "192.168.0.181"
}
]
}
MY PHP
$out = json_decode($json_data, true);
$x= count($out);
echo $x;
The value that I get is 1 instead of 2. And as you can see I have an associative array. I was trying to print those datas.
for($i=0; $i<$x; $i++)
{
echo $out['action'];
echo $out['user'][$i]['firstName'] ;
echo $out['user']['type'][$i]['typename'] ;
}
I don't get output. HELP???
I think it may be counting just the "Log"... technically that response is 2 dimensional:
data[0] = log
data[0][0] = log.firstRecord
data[0][1] = log.secondRecord
Try iterating through the second dimension
you have 2 element inside log key in your array.
try this:
$x= count($out['log']);
this will count 2
demo
for your loop you should try like this:
$out = json_decode($json_data, true);
$x= count($out['log']);
$out = $out['log'];
for($i=0; $i<$x; $i++)
{
echo $out[$i]['action'];
echo $out[$i]['user']['firstName'] ;
echo $out[$i]['user']['type']['typename'] ;
}
complete demo

Categories