PHP preg_replace a json stringified object - php

i have a regex challenge i can't solve on my own, i have a json stringified file that hold lots of entries so instead of decoding it and looping over all items i want just use a preg_replace to delete a specific item with specific id.
so my json look like this:
[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
}
]
what i know is the id part so i can do something like this
preg_replace('/{\"id\"\:\"440\".*?\"},/', '', $jsonBlob);
unfortunately my regex don't keep in count the last item that doesn't end with comma , but with a bracket ]
any help is really appreciated. thanks in advance.

Loop through JSON example using the id, in your case you don't need to use unset().
$json = '[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
}
]';
$arr = json_decode($json,true);
foreach($arr as $key => $value) {
if($value['id']==436) {
unset($arr[$key]); // delete this entry from results
// $value = your_new_json_object {id,type,..}
}
}
print_r($arr);
Fiddle

Would you mind to try this Function and see if it does the trick for you?
<?php
// PASS IN THE ID YOU WANNA FILTER-OUT AS $id,
// 2ND PARAMETER IS THE JSON STRING
// 3RD PARAMETER IS THE REPLACEMENT STRING: IN YOUR CASE EMPTY: ""
function removeJsonBlock($id, $jsonSTR, $replacement="YEAH!!! IT WORKS!!!"){
$jsonSTR = trim($jsonSTR);
$filteredJson = preg_replace('#(\{\s*)([\'\"]id[\'\"]\:)(\s?[\'\"])' . trim($id) . '([\'\"])([\w,\.;\"\'\-\?\:\s_\n\r]+)(\},?)#si', $replacement, $jsonSTR);
return $filteredJson;
}
// THE JSON STRING IN QUESTION - REGARDLESS OF WHETHER DYNAMIC OR NOT.
$jsonSTR =<<<JSS
[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
},
// ADD ANOTHER NODE WITH THE SAME ID OF 440 FOR EXAMPLE...
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
]
JSS;
// TEST THE SIMULATION... IT SHOULD REMOVE EVERY ENTRY WITH ID: 440
var_dump(removeJsonBlock(440, $jsonSTR));
//
I hope it helps in a little bit.... ;-)

You can use this regex:
{\s*"id":"440"[^}]*}
As a string that's:
$re = "/{\\s*\"id\":\"440\"[^}]*}/im";
This assumes that id is the first value in the JSON array, but it will account for whitespace. It uses [^}]* to grab everything up to the }.
Since you're looking to delete the item, the regex can be changed to look for commas before or after the match. I have also included a way for the item to match if it is the only thing in the array:
,\s*{\s*"id":"440"[^}]*}|{\s*"id":"440"[^}]*}\s*,|{\s*"id":"440"[^}]*}
It's easier to read with x spacing enabled:
,\s*{\s*"id":"440"[^}]*} |
{\s*"id":"440"[^}]*}\s*,|
{\s*"id":"440"[^}]*}

Related

How to remove the unwanted nested keys from JSON

This is my json:
{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}
I want to remove the second level keys (e.g "26:" and "28":) using PHP.
In other words, I want to replace the double-quoted number keys with zero-indexed numeric keys.
How can I make it look like this:
{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}
Here is the demo.
Code:
// declare $json
$array=json_decode($json,true); // decode as array
// overwrite subarray with zero-indexed keys while preserving subarray values
$array['all_counts_reports']=array_values($array['all_counts_reports']);
var_export(json_encode($array)); // return to json
Input:
$json='{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}';
Output:
'{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}'
In your javascript, use JSON.parse() to strip the wrapping single quotes:
var str='{"all_counts_reports":[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]}';
var json=JSON.parse(str);
console.log(json);
And because we are running with assumptions, if you want to remove the all_counts_reports key as well, you can use this one-liner:
Code:
$new_json=json_encode(array_values(current(json_decode($json,true))));
Output:
'[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]'
$array = json_decode($your_json_string,true);
print_r($array);
$result = array();
foreach($array['all_counts_reports'] as $rep){
$result['all_counts_reports'][] = array(
"name"=>$rep['name'],
"date"=>$rep['date'],
"trips_per_day"=>$rep['trips_per_day'],
"cash_trips"=>$rep['cash_trips'],
"credit_trips"=>$rep['credit_trips'],
"compliment_trips"=>$rep['compliment_trips'],
);
}
$result_json = json_encode($result);
echo $result_json;
There may be better solution, but this one is right now in my mind
Its unclear that what you looking for, if you just want to remove and dont want to maintain as original json then you can do like this example. But if you dont want your all_counts_reports treated as array [] then this example will not help.
And simply pass to android then above will work.

Get a key from an JSOn object inside another JSON object only knowing it's position [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed last year.
So I have the following JSON Object as an example:
{
"employees": {
"employee300": {
"number" : "example",
"Name" : "example",
"position" : 1
},
"employee456": {"number" : "example",
"Name" : "example",
"position" : 2},
"employee120":{"number" : "example",
"Name" : "example",
"position" : 3}
}
}
I only have the position and I want to get the employee's id. For example, I have the position number that is 2 and I need to get the id that is "employee456".
I know there are a lot of key functions in PHP, but I would like to know how I can make my code work in my scenario.
I can also convert the json to an array if there is a solution to it that way.
I'm not sure whether you want to do this in JS or PHP, going to assume the latter.
<?php function get_employee_at_pos($employees, $pos)
{
foreach ($employees as $key => $value) {
if ($value['position'] == $pos) {
return $key;
}
}
return false;
}
use var keys = Object.keys(obj) to get the keys, then use the myobject[keys[1]]. (1 corresponds to position - 1).
EDIT: in php
$keys = array_keys(myobject); and use $myobject[$keys[1]]
EDIT 2: in php, you need to load the json in an array
$myjson = json_decode(file_get_contents("yourfile.json"), true); // loads yourfile.json and converts to a php array.

PHP and JSON/ How to get a specific elements //

I need to parse a JSON file. I've only worked with XML before.
How can I get the second "food_id" (1730905)?
Here is my JSON file:
{
"shopId":29,
"last":46977914,
"freshfood":[
{
"freshfood_id":2629,
"food":[
{
"food_id":1740851,
"type":"fruit",
"status":1
},
{
"food_id":1730905,
"type":"vegetable",
"status":1
},
]
}
]
}
I tried this, but it does not work.
$string = file_get_contents("food.json");
$json_a=json_decode($string,true);
echo $GetFreshFoodId = $json_a['freshfood'][1]['freshfood_id'];
PHP arrays are zero-based, so that should be:
$json_a['freshfood'][0]['food'][1]['food_id'];
Also, note that the JSON is not entirely valid - you should remove the last comma. (But you might have left out additional records in your example JSON for clarity.)

PHP JSON getting specific value of each key

I have a php code that reads JSON files. Part of the JSON sample below:
"Main": [{
"count": 7,
"coordinates": [89,77],
"description": "Office",
},{
"count": 8,
"coordinates": [123,111],
"description": "Warehouse",
}]
and I am trying to code PHP to only get the info (count, coordinates, description) of those who's description is included in the criteria like Warehouse. PHP Sample below
$validcriteria = array("Warehouse", "Parking_lot");
How do I do an if-statement to check first if "description" is included in the valid criteria. I tried the code below but it doesn't seem to work right.
$JSONFile = json_decode($uploadedJSONFile, false);
foreach ($JSONFile as $key => $value)
{
if (in_array($key['description'] , $validcriteria))
{
#more codes here
}
}
My code in PHP has been working except when I try to add $key['description'] to try and check the description first if it's valid. My code above is reconstructed to remove sensitive information but I hope you got some idea of what I was trying to do.
When attempting to understand the structure of a parsed JSON string, start with a print_r($JSONFile); to examine its contents. In your case, you will find that there is an outer key 'Main' which holds an array of sub-arrays. You will need to iterate over that outer array.
// Set $assoc to TRUE rather than FALSE
// otherwise, you'll get an object back
$JSONFile = json_decode($uploadedJSONFile, TRUE);
foreach ($JSONFile['Main'] as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value['description'], $validcriteria))
{
// Do what you need to with it...
}
}
Note: if you prefer to continue setting the $assoc parameter to false in json_decode(), examine the structure to understand how the objects lay out, and use the -> operator instead of array keys.
$JSONFile = json_decode($uploadedJSONFile, FALSE);
foreach ($JSONFile->Main as $value)
{
// The sub-array $value is where to look for the 'description' key
if (in_array($value->description, $validcriteria))
{
// Do what you need to with it...
}
}
You might also consider using array_filter() to do the test:
$included_subarrays = array_filter($JSONFile['Main'], function($a) use ($validcriteria) {
return in_array($a['description'], $validcriteria);
});
// $included_subarrays is now an array of only those from the JSON structure
// which were in $validcriteria
Given your JSON structure, you probably want
foreach($decoded_json['Main'] as $sub_array) {
if (in_array($sub_array['description'], $validation)) {
... it's there ...
}
}
Because you set false to second argument of json_decode function, it's returned as an object,
if you change it to TRUE, the code would work.
http://php.net/manual/en/function.json-decode.php
and you have to change key to value;
foreach ($JSONFile->Main as $key => $value)
{
if (in_array($value->description, $validcriteria))
{
#more codes here
}
}
this code assume your json file has one more depth greater than your example. that's why $JSONFile->Main in the foreach loop.
Try to use that :
if ( array_key_exists('description', $key) )

datatables and json formatting error with php

HI im having a little difficulty with dataTables and php. I'm echoing out json in the format below:
{"iTotalRecords":10,"iTotalDisplayRecords":10,"aaData":[[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:00:00"],[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:18:59"] ... ] }
Which inst working with my dataTable, However after validating the above in jsonlint.com/, i get the well formated version below:
{
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [
[
"1",
"15",
"1",
"long description long description long description long description",
"2012-02-25 00:18:59"
],
...
]
}
When I put this in a txt file it loads just fine. I also noticed that adding a line break in the "long description" part, it also doesn't work even with the one above. My guess is that the line break is messing with the format of the json, but how can I avoid this in my php script since everything is being word wrapped? I've tried \n in my echo code but it doesnt seem to create a newline.
The opening and closing curly braces { and } are not acceptable to DataTables. My guess is, it's considered an object rather than an array. Try this:
Use the following php function to create your JSON array:
$this->arrayJSON = $this->arrayPHPToJS($myArray);
public function arrayPHPToJS($phpArray) {
if (is_null($phpArray)) return 'null';
if (is_string($phpArray)) return "'" . $phpArray . "'";
if (self::is_assoc($phpArray)) {
$a=array();
foreach ($phpArray as $key => $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
if (is_array($phpArray)) {
$a=array();
foreach ($phpArray as $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
return json_encode($phpArray);
}
Use this array in JS script in your view (make sure there's no html escaping):
<script type="text/javascript">
var jsArray = <?php echo $arrayJSON; ?>;
$(function(){
var oTable = $('#mytable').dataTable( {
"aaData": jsArray,
....
});
});
</script>
sounds more like the number of columns set up in table/datatables doesn't match number of items in your json array
There seemsed to be an issue with one of my database values, it was starting on a new line, which cause the format of the json to be incorrect.

Categories