JSONPath Query to get Node-names? - php

Consider the following piece of JSONPath:
{
"result":[
{
"type":"Residence",
"street":"Piazza di Spagna",
"city":"-4:0"
},
{
"type":"Residence",
"street":"test",
"city":"-4:1"
}
]
}
Is it possible to get a list of all the node-names?
So for example, I want a list like: type, street, city.

Try this
$arr = (json_decode($json)->result[0]);
$array = get_object_vars($arr);
$properties = array_keys($array);
print_r($properties);`
Out put will be
Array
(
[0] => type
[1] => street
[2] => city
)

On PHP >= 5.4 you can obtain your keys with one line of code:
$nodeNames = array_keys( json_decode( $jsonString, True )['result'][0] );
3v4l.org demo
On lower versions (PHP >= 5.2.16), you have to break above code in two lines:
$array = json_decode( $jsonString, True );
$nodeNames = array_keys( $array['result'][0] );
I decode the JSON string with second parameter as True to force result as array, then I call array_keys to obtain the keys of array['result'][0].
Edit: more flexibility
Your example can be processed as above without problems, but what happens if original JSON string has different keys? The above solution will fail if in the first result row there are not all the keys. To obtain all the keys, you can use this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
foreach( $array['result'] as $row )
{
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
or, using array_filter, with this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
array_filter
(
$array['result'],
function( $row )
{
global $nodeNames;
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
);
By this two equivalent examples, I process each result row, merging the keys in $nodeNames array and using array_unique to delete duplicate keys.
Read more about array_keys()
Read more about array_unique()
Read more about array_filter()

You can use following function to print all keys in an array format
print_r(array_keys($array));

Is the JSON Path definitely going to follow that structure every time? As in Result => Arrays all of which have the same Nodes.
If it does then the following will work:
function getJsonNodes($json) {
$nodes = array();
$decoded = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid JSON String passed to getJsonNodes()');
}
$result = $decoded['result'];
if (is_array($result)) {
$nodes = array_keys($result[0]);
}
return $nodes;
}
Usage would be something like:
try {
$nodes = getJsonNodes($json);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage();
}
Means you can catch any Invalid JSON strings that could potentially be passed and mess with the output.
Although as I stated, the above solution will only work if your JSON Path follows the structure to put in your OP.
You can see it in use here: https://ideone.com/dlvdu2
Hope it helps either way.

Is it possible to get a list of all the node-names?
$object = json_decode($json);
$json_array = $object->result;
foreach ($json_array as $key => $value) {
$object_var = get_object_vars($value);
$object_key = array_keys($object_var);
var_dump($object_key);//will get all node_names!
}

Try this
$result[0].type , $result[0].street, $result[0].city

Please check the below code ..Hope will work
<?php
$text[]=array(
result=>array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
),
array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
)
);
echo json_encode($text);
?>

Related

How to filter JSON in php?

i have this JSON
[
{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}
]
I want to get only those with this ID 2513
[
{"name":"Maria";"Sex":"Female","ID":"2513"}
]
Your JSON String is invalid. First replace all the semicolons ; with comma , and then try using array_filter() or any other way e.g foreach() with if condition etc. I've used the array_filter() way, hope it helps :)
<?php
$json = '[{"name":"Juan","Sex":"Male","ID":"1100"},{"name":"Maria","Sex":"Female","ID":"2513"},{"name":"Pedro","Sex":"Male","ID":"2211"}]';
$array = json_decode($json,1);
$ID = 2513;
$expected = array_filter($array, function ($var) use ($ID) {
return ($var['ID'] == $ID);
});
print_r($expected);
?>
DEMO: https://3v4l.org/kZrMo
Use json_decode() to convert the JSONString to a PHP array of objects
$str = '[{"name":"Juan","Sex":"Male","ID":"1100"},"name":"Maria";"Sex":"Female","ID":"2513"},{"name":"Pedro";"Sex":"Male","ID":"2211"}]';
$arr = json_decode($str);
foreach ( $arr as $obj ){
if ( $obj->ID == 2513 ) {
echo $obj->name;
}
}

preg match from json decoded page

I have one json decoded page and i want to scrap some data from that page.
I need to scrap this "value": "6fc975cd-bbd4-2daa-fc6b-1e8623f80caf|Antennas & Filter Products|Filter Products"
this is my json page
This is my function for preg match
public function getcategories( $page = '' ) {
$results = array();
preg_match_all( '~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall );
debug($matchall);die;
if ( !empty( $matchall[1] ) ) {
foreach ( $matchall[1] as $single ) {
if ( strlen( $single ) > 1 ) {
$results[] = $single;
}
}
}
return $results;
}
And i call this function here
function checkpage( $page = '' ) {
$vars_all_array = $this->getvarsallfrompage( $page );
$get_api_url = $this->catspostreq($page);
$post_data = $this->makePostData( $vars_all_array, 0, 25 );
$jsonpage = $this->get_page( $get_api_url, array ('data' => $post_data, 'content-type'=> 'application/x-www-form-urlencoded; charset="UTF-8"; application/json' ) );
$json_decoded = json_decode($jsonpage);
$categories = $this->getcategories( $json_decoded );
debug($categories);die;
}
But something not working good, i have this error:
preg_match_all() expects parameter 2 to be string, array given
Can someone help me?
You don't need to do a preg_match_all to get the value out of $json_decoded, as json_decode() will return (if successfull) a perfectly readable array or object.
So to get the one specific value you can access it like so:
$value = $json_decoded['groupByResults'][0]->values[0]->value;
Since you want to have all the values in a new array, you could just iterate the values and pass it to a new array:
$categories = [];
foreach($json_decoded['groupByResults'][0]->values as $item) {
$categories[] = $item['value'];
}
There are built in array-functions that do that in one line and maybe quicker. This is to illustrate what you are doing with the data.
Using such a function array_column() would result in this one-liner:
$categories = array_column($json_decoded['groupByResults'][0]->values, "value");
Within your checkpagefunction you pass the value of json_decode to the getcategories function as parameter which return in most of case an array. and your getcategories you pass the $page parameter as a second parameter of preg_match_all
$json_decoded = json_decode($jsonpage);
$categories = $this->getcategories( $json_decoded );
and in your getcategories
preg_match_all('~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall);
here $page is the result of json_decode which is an array. that why you are getting that error

Removing non-unique JSON object from file using PHP [duplicate]

I need one help.I have some JSON type data and i want to remove the duplicate set of data using PHP.I am explaining my code below.
data=[
{'member_name':member1,'no_of_users':20},
{'member_name':member1,'no_of_users':20},
{'member_name':member1,'no_of_users':20},
{'member_name':member2,'no_of_users':10},
{'member_name':member2,'no_of_users':10},
{'member_name':member3,'no_of_users':30},
]
my php side code is given below.
$res[]=array('member_name'=>$member,'no_of_members'=>$rowno['cnt']);
$result=var_dump( array_unique( $res, SORT_REGULAR ) );
//$result = json_decode($array, TRUE );
print json_encode($result);
Here we can see many duplicate data available.I need to remove only the duplicate data from this JSON object using PHP.Please help me.
First json_decode the JSON string, so we can work with it in PHP. Then you should use array_unique with the flag SORT_REGULAR to remove all duplicates and lastly json_encodeit again to a JSON string. Here's a working example:
$data = '[
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member2","no_of_users":10},
{"member_name":"member2","no_of_users":10},
{"member_name":"member3","no_of_users":30}
]';
// Make a PHP array from the JSON string.
$array = json_decode( $data, TRUE );
// Only keep unique values, by using array_unique with SORT_REGULAR as flag.
// We're using array_values here, to only retrieve the values and not the keys.
// This way json_encode will give us a nicely formatted JSON string later on.
$array = array_values( array_unique( $array, SORT_REGULAR ) );
// Make a JSON string from the array.
$result = json_encode( $array );
Edit:
Based on your edit in your question:
Don't assign $result to a var_dump. Replace $result=var_dump( array_unique( $res, SORT_REGULAR ) ); by $result=array_unique( $res, SORT_REGULAR );
I was faced with the same challenge, so I came up with this simple solution.
<?php
//UniqueValues.php
class UniqueValues{
#The data Array
private $dataArray;
/*
The index you want to get unique values.
It can be the named index or the integer index.
In our case it is "member_name"
*/
private $indexToFilter;
public function __construct($dataArray, $indexToFilter){
$this->dataArray = $dataArray;
$this->indexToFilter = $indexToFilter;
}
private function getUnique(){
foreach($this->dataArray as $key =>$value){
$id[$value[$this->indexToFilter]]=$key;
}
return array_keys(array_flip(array_unique($id,SORT_REGULAR)));
}
public function getFiltered(){
$array = $this->getUnique();
$i=0;
foreach($array as $key =>$value){
$newAr[$i]=$this->dataArray[$value];
$i++;
}
return $newAr;
}
}
?>
include the class in your invocation code and that's all
<?php
//index.php
include_once('UniqueValues.php');
#Your JSON data
$data = '[
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member1","no_of_users":20},
{"member_name":"member2","no_of_users":10},
{"member_name":"member2","no_of_users":10},
{"member_name":"member3","no_of_users":30}
]';
#Convert your JSON to Array
$array = json_decode( $data, TRUE );
/*
Create an object by passing the "Two Dimension Array" in this case "$array" and
the "index" in this case "member_name" that you want to get the Unique Values
*/
$supper = new UniqueValues($array,"member_name");
/*
Get the unique valued array by calling the getFiltered() function
and encode it to JSON
*/
$result = json_encode( $supper->getFiltered() );
#Let the World See it :)
echo $result;
?>
Here, how can I solve this. See with example. make json unique
code part:
<?php
$depositeArray = array( 'deposite'=>array(
array('email'=>"sajib#gmail.com", 'deposite'=>0),
array('email'=>"avi#gmail.com", 'deposite'=>0),
array('email'=>"iqbal#gmail.com", 'deposite'=>0),
array('email'=>"balla#gmail.com", 'deposite'=>0),
array('email'=>"sajib#gmail.com", 'deposite'=>0),
array('email'=>"razib#gmail.com", 'deposite'=>0)
),
'total'=>0);
$depositeArray = json_encode($depositeArray);
$depositeArray = json_decode($depositeArray,true);
$depositeArrayNew = Json_Super_Unique($depositeArray['deposite'],'email');
$depositeArray['deposite'] = $depositeArrayNew ;
echo json_encode($depositeArray);
function Json_Super_Unique($array,$key){
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
?>

PHP: Check duplicate array key in objects array.

I have an objects array as following
[{"ChannelName":"39-40","Text":"haha"},
{"ChannelName":"39-40","Text":"lala"}
{"ChannelName":"40-41","Text":"bla bla"},
{"ChannelName":"40-41","Text":"kha kha"}]
How can I check duplicate value in ChannelName. What I need to do is when ChannelName exists in array object, I want to replace the ChannelName with new Text. How php check duplicate ChannelName and how to replace of old Text attribute with new Text attribute if ChannelName duplicate?
Try this solution.
$json = <<<JSON
[{"ChannelName":"39-40","Text":"haha"},
{"ChannelName":"39-40","Text":"lala"},
{"ChannelName":"40-41","Text":"bla bla"},
{"ChannelName":"40-41","Text":"kha kha"}]
JSON;
$json_array = json_decode( $json, TRUE );
$new_array = array();
$exists_array = array();
foreach( $json_array as $element ) {
if( !in_array( $element['ChannelName'], $exists_array )) {
$exists_array[] = $element['ChannelName'];
}
else{
$element['ChannelName'] = 'New Value';
}
$new_array[] = $element;
}
print json_encode( $new_array );
Here at New Value section you can change your value as per your requirement.

How to edit JSON objects

I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]

Categories