PHP json_decode thrown an error for validate json string - php

I have following error
Notice: Trying to get property of non-object in action.php
while posted json has validated (by jsonLint.com validation).
Here is my json string:
[
{
"eTGid": "1",
"eTid": "34",
"evrakGelisTarihi": "12/12/2013",
"evrakKonu": "Sertifika denemesi",
"evrakKurumID": "1047",
"evrakCikisTarihi": "13/12/2013",
"evrakCikisSayisi": "313213213213",
"aciklamaBolumu": "açıklayıcı notlar",
"gelenEvrakTarihi": "30/12/2013",
"gelenEvrakSayisi": "3132321",
"gelenEvrakEtakipNo": "987654",
"bagliIlaclar": "[\"0\",\"[{\\\"ilacID\\\":\\\"744\\\",\\\"ilacPN\\\":\\\"asdasd2132\\\",\\\"ilacSKT\\\":\\\"12/12/2013\\\"}]\"]",
"bagliFirmalar": "[\"0\",\"[{\\\"firmaID\\\":\\\"1047\\\"}]\"]",
"": "[\"0\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"asdasda\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"2\\\",\\\"ilacIhracADI\\\":\\\"ABFADER\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"10\\\"}]\",\"[{\\\"bankaID\\\":\\\"5\\\",\\\"makbuzNO\\\":\\\"ASDAWW\\\",\\\"makbuzTARIHI\\\":\\\"12/12/2013\\\",\\\"ihracaatYapilacakUlkeID\\\":\\\"191\\\",\\\"ilacIhracADI\\\":\\\"ABFADEX\\\",\\\"makbuzTUTAR\\\":\\\"202,06\\\",\\\"makbuzTipDetayDEGERİ\\\":\\\"9\\\"}]\"]",
"bagliMakbuzlar": "[\"0\",\"987654»12/12/2013»3213213\"]",
"kurumIcimi": "hayir"
}
]
and my php code is:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj->{'eTGid'});
Where did I go wrong?
After suggestions:
My Json string has arrived to the serverside (php) as an array (between brackets).
Array has only one element (member) that it is our json string (object)
Handle the arrays first element and assign it to a php object and deal with it.
$gelenJsonVerisi = $_POST['yeniEvrak'];
$yeniEvrakObjArray = json_decode($gelenJsonVerisi,TRUE);
$yeniEvrakObj = $yeniEvrakObjArray[0];
exit($yeniEvrakObj['eTGid']); // one of sample value
Thank you

The JSON string shows an array, that contains a single object. access the data like so:
$yeniEvrakObj = json_decode($gelenJsonVerisi);
echo $yeniEvrakObj[0]->eTGid;
If you're sure there's but 1 object inside that array, you could try:
$yeniEvrakObj = json_decode(
substr($gelenJsonVerisi,1,-1)
);
Which chops off the leading and terminating brackets. This implies no leading of trailing whitespace, so trim the string first.
check codepad. As you can see, the json_decode call returns the data as an array containing an object:
Array
(
[0] => stdClass Object
(
[eTGid] => 1
[eTid] => 34
[evrakGelisTarihi] => 12/12/2013
[evrakKonu] => Sertifika denemesi
[evrakKurumID] => 1047
[evrakCikisTarihi] => 13/12/2013
[evrakCikisSayisi] => 313213213213
)
)

It's not json_decode throwing the error, it's when you try to access the resulting array. Yes, that's right, array. Your JSON value is this:
[ { ... } ]
^ array ^
So you need to access the result like:
$yeniEvrakObj[0]->eTGid

$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);

The problem is the way you're trying to access to the decoded object, as it is inside an array.
Your code should be:
$gelenJsonVerisi = $_POST['yeniEvrak'];
echo($gelenJsonVerisi);
$yeniEvrakObj = json_decode($gelenJsonVerisi);
exit($yeniEvrakObj[0]->eTGid);
Edit: Thanks for the comments on this answer that made me see I was mistaken

Related

How to solve array push problem in laravel

i have a Two fields 1. allowances which is contain this data
{"medical":"600","transport":"350","food":"900"}
and another one 2. house rent which is contain this data
2550.00
now i want to get a result in third column like this
{"medical":"600","transport":"350","food":"900","house_rent":"2550.00"}
so far i tried this
$allowances=json_decode($salary->allowances);
$house_rent = array('House Rent' => $salary->house_rent);
$allowances_logs=array_push($allowances,$house_rent);
$salary->allowances_logs = $allowances_logs;
but it gives me following error"array_push() expects parameter 1 to be array, object given". Help me achieve this result. Any help will be appreciated
First, add true as second argument to json_decode(), and you will retrieve the results as an array instead of an object.
Second, with the two arrays, do:
$merged = array_merge($arr1, $arr2);
true Add second argument in json_decode(), so you can see below example
$mainArr = json_decode('{"medical":"600","transport":"350","food":"900"}',true);
$house_rent = array('House Rent' => 2550.00);
$printArr = array_merge($mainArr, $house_rent);
print_r(json_encode($printArr));
Output
{"medical":"600","transport":"350","food":"900","House Rent":2550}
First convert your json to array.
You can do this with json_decode php function.
json_decode function convert your json to object or associative array.
First argument on this function is the json string being decoded.
When is second argument are TRUE, returned objects will be converted into associative arrays.
$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);
Output - Array ( [medical] => 600 [transport] => 350 [food] => 900 )
Now you can add new item to your array.
$testArr['house_rent'] = '2550.00';
Your array now look like this.
Array ([medical] => 600 [transport] => 350 [food] => 900 [house_rent] => 2500.00)
At the end you convert your array to json. For this you can use php json_encode function.
$testJson = json_encode($testArr);
Full Example
$testJson = '{"medical":"600","transport":"350","food":"900"}';
$testArr = json_decode($testJson, true);
$testArr['house_rent'] = '2500.00';
$testJson = json_encode($testArr);
echo $testJson;

How can I parse/extract from a string in PHP? Specifically something between quotes

I have a string like this
{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}
How do I get for example, the content inside value to a variable? And I would want to be able to get it for every item with value in there. There will be several that come from a form in a single string.
This is the response from a form that stores the whole string in a string. Kinda wish it was an array but this is what i'm working with.
Your string is actually a JSON value. To get the data out of it, you must first json_decode it to an array (or object). If you choose an array, you can then use array_column to get all the 'value' values:
$json = '{"2":{"name":"Moon Center","value":"moon7","value_raw":"moon7","id":2,"type":"select"},"3":{"name":"Multiple Choice","value":"Second Choice","value_raw":"Second Choice","id":3,"type":"radio"}}';
$array = json_decode($json, true);
print_r(array_column($array, 'value'));
Output:
Array (
[0] => moon7
[1] => Second Choice
)
Demo on 3v4l.org

php variable converting to JSON object

I want to make an array of json objects having the structure as follows:
{
"client-mac": "0C:D2:B5:68:73:24",
"client-dbm": "-82",
"clientManuf": "unknown"
}
I am using following php code to get this result:
$clientMac = $clients->{'client-mac'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'};
$clientManuf = $clients->{'client-manuf'};
$jsonObject = array('client-mac' => $clientMac,
'client-dbm' => $clientStrength,
'clientManuf' => $clientManuf);
$jsonString = json_encode($jsonObject);
The problem is I am getting following json string:
{"client-mac":{
"0":"0C:D2:B5:68:73:24"
},
"client-dbm":{
"0":"-82"
},
"clientManuf":{"0":"Unknown"}
}
Why I am getting those extra keys as "0"? And how can I get my desired output? Thank you in advance :)
Apparently your source data has one more nested level with one key/value pair.
You could use reset on them to just pick the first value from that:
array('client-mac' => reset($clientMac),
'client-dbm' => reset($clientStrength),
'clientManuf' => reset($clientManuf));
That's because $clientMac, $clientStrength and $clientManuf are objects, not literal strings. You have to change the first three lines in the following way,
$clientMac = $clients->{'client-mac'}->{'0'};
$clientStrength = $clients->{'snr-info'}->{'last_signal_dbm'}->{'0'};
$clientManuf = $clients->{'client-manuf'}->{'0'};
...

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

JSON decode with PHP: Key started with # sign

JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];

Categories