Getting JSON data with PHP - php

Apologies if this has been asked a thousand times, but I can't find a good tutorial on how to do this correctly and searching on Stack is coming up trumps.
I have a JSON file which has data like this:
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
{
"store":"Store 1",
"cat":"Categories",
"general_cat":"Categories",
"spec_cat":"Accessories"
},
with about 50 entries in it. I'm trying to parse this data and store the values in variables.
So far I've tried:
$string = file_get_contents("jsonFile.json");
$json_array = json_decode($string,true);
foreach ($json_array as $key => $value){
$store = $key -> store;
$general_cat = $key -> general_cat;
$spec_cat = $key -> spec_cat;
if (!is_null($key -> mainImg_select)){
$cat = $key -> cat;
}
echo $headURL;
}
This is resulting in "Trying to get property of non object" errors. What am I doing wrong here?

The second argument of json_decode tells the function whether to return the data as an object, or an array.
Object access uses the -> symbol. To return an object from json_decode either use json_decode($jsonString) or json_decode($jsonString, false) (the second argument is false by default)
$jsonString = '{ "this_is_json" : "hello!" }';
$obj = json_decode($jsonString);
echo $obj->this_is_json // "hello!";
You can also access your json data as an array by setting the second argument to true
$jsonString = '{ "this_is_json" : "hello!" }';
$arr = json_decode($jsonString, true);
echo $arr['this_is_json'] // "hello!";
What can be a little more conceptually confusing, is that PHP json_decode can return either an array of objects (rather than just an object), or an associative array.
Consider the following json string. This string represents a "collection" (square brackets) of json data structures (curly braces).
[
{
"name": "One"
},
{
"name": "Two"
}
]
If we assign this json to the variable $string hopefully this will illustrate the difference
$asObjects = json_decode($string);
$asAssociativeArray = json_decode($string, true);
foreach ($asObjects as $obj) {
echo $obj->name;
}
foreach ($asAssociativeArray as $arr) {
echo $arr['name'];
}

It seems like you are requesting an associative array (by passing True as the second parameter to the json_decode function) but trying to use it as an object.
Try $json_array = json_decode($string,false); . That will return objects
Also, as #MatRt mentions, you need to use $value instead of $key to reference the objects

You need to retrieve values with array syntax:
$item['key']
as apposed to
$item->key

Related

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
]

Loop through JSON and store values to PHP arrays

I have a JSON with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?
$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.
<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));
You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));
You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode
Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}
After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.

How to get values of a json array in php?

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?
$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo
You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

loop json array and return values in php

I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync. I use PHP: 5.4.7
this is json var $json
{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}
when I try to get the values
$js=json_decode($json,true);
foreach ($js['formaspago'] as $row ) {
echo $row["Formapago"];
}
I get this error:
Invalid argument supplied for foreach
any help is appreciated
use json_decode
//array
$data = json_decode($json, true);
foreach($data["data"]["formaspago"] as $row) {
echo $row["Formapago"];
}
Thanks #JimL for the hint.
You're not passing a valid array to the foreach loop. However, even if you parse the json you've supplied, a foreach won't work because it's an object not an array.
$json = '{
"info":"",
"data":{
"clientes":[],
"conceptos_gastos":[],
"formaspago":[{
"idFormaPago":7,
"FormaPago":"quwuw",
"Dias":1,
"Cuotas":1,
"last_sync_date":null
}],
"listaprecios":[],
"producto":[],
"repartidores":[],
"tipodocumento":[],
"vehiculos":[],
"zonas":[]
}
}';
$obj = json_decode($json);
print $obj->info will return an empty string.
$obj->data is an object that has various properties some of which are empty arrays. Passing these into the foreach should work. i.e.
foreach($obj->data->clients as client) {
// Do something here
}
Further, $obj->data->formaspago has exactly one element in the array, which is an object. You can access this object with a foreach loop:
foreach($obj->data->formaspago as formaspago) {
print formaspago->idFormaPago; // Will print 7
print formaspago->FormaPago; // Will print "quwuw"
print formaspago->Dias; // Will print 1
print formaspago->Cuotas; // Will print 1
print formaspago->last_sync_date; // Will print nothing
}

How do I iterate through an stdObject's array?

Like in Java when you iterate a list, it's real easy, it's like: while(BLAH.hasNext()) { }, so how do I do that in PHP when I have an array within an stdObject that I want to iterate through each and every item?
I keep getting Catchable fatal error: Object of class stdClass could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 29
<?php
$apiUrl = 'https://api.quizlet.com/2.0/groups/44825?client_id=***BLOCKED FROM PUBLIC***&whitespace=1';
$curl = curl_init($apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($curl);
if ($json) {
$data = json_decode($json);
echo "<h1>Sets from \"{$data->name}\"</h1>";
foreach ($data->sets as $key => $val) {
echo "$key: $val\n";
}
echo "</ul>";
var_dump($data);
}
?>
You can/should use foreach to iterate over every element of an array.
$foo = new stdClass;
$foo->arr = array('1','7','heaven','eleven');
foreach ($foo->arr as $val)
{
if (is_object($val)) var_dump($val);
else echo $val;
}
Note the line I added to var_dump sub-objects. The error you were initially getting was that the elements of your sets array were also objects, not strings as expected. If you only need to access certain elements of the set objects, you can access them using $val->property.
For example you have an object like
$obj = new stdClass;
$obj->foo = 'bar';
$obj->arr = array('key' => 'val', ...);
$array = (array) $obj;
now you can use foreach to iterate over array.
foreach($array as $prop) {
//now if you are not sure if it's an array or not
if(is_array($prop)) {
foreach($prop as $val)
//do stuff
}
else {
//do something else
}
}
The $val variable holds another object (of type stdClass) which contains the details for an individual "set". As you can see, since it generates an error, you cannot echo a stdClass object.
You can access the values inside each object using the object->property notation that you seems to be getting familiar with. For example.
foreach ($data->sets as $set) {
echo $set->title . " by " . $set->created_by . "<br>";
}
/*
An example of the JSON object for a single $set
Access these like $set->title and $set->term_count
{
"id": 8694763,
"url": "http:\/\/quizlet.com\/8694763\/wh-test-1-2-flash-cards\/",
"title": "WH Test 1 & 2",
"created_by": "GrayA",
"term_count": 42,
"created_date": 1323821510,
"modified_date": 1323821510,
"has_images": false,
"subjects": [
"history"
],
"visibility": "public",
"editable": "groups",
}
*/

Categories