Json decode returns null value - php

i know this question ask many time before but still i could't get this working.
i have a json and when i dump $TenentsAccessible output is this
string(71) "[{`TenantID`:`test.com`,`Name`:`12thdoor`}]"
i need to get the value inside TenantID property. so i use json decode to convert this to php array but is returns null
$jnTenant = json_decode($TenentsAccessible,TRUE);
$tenantID = $jnTenant["TenantID"];
var_dump($jnTenant); // this return null
i try to remove the &quot and unwanted characters using this
$TenentsAccessible = str_replace('"', '"', $TenentsAccessible);
$TenentsAccessible=preg_replace('/\s+/', '',$TenentsAccessible);
i know this type of question ask before but i still could't get this to work. appropriate the hlep. thanks

you can check your json code on JsonLint.
I tried your code and it's not correct because of backticks (`).
So you should replace with (") to have
[{
"TenantID": "test.com",
"Name": "12thdoor"
}]
As hasan described in his answer, json_decode returns a multi-dimensional array, so to get TenantID:
$jnTenant = json_decode('[{"TenantID":"test.com","Name":"12thdoor"}]',true);
$tenantID = $jnTenant[0]['TenantID'];
var_dump($tenantID) ;
If you want to get the "TenantID" in the way you described, you have to modify (if you can) the json like this
{
"TenantID": "test.com",
"Name": "12thdoor"
}
Hope it helps.

try it :
$jnTenant = json_decode('[{"TenantID":"test.com","Name":"12thdoor"}]',true);
$tenantID = $jnTenant[0]['TenantID'];
var_dump($tenantID) ;
correct json and corect get json !
for understand this plz print_r( $jnTenant );
this varibale is Two-dimensional array .

Related

How to get value from JSON encode in PHP?

i have searched and searched but i don't know where i'm wrong getting a value from JSON encode, can you help me? Please don't kill me, i'm a newbie :)
My php:
<?php
$data = json_decode("document.json", true);
$getit = $data["likes"];
My JSON:
[{
"title" : "MYTITLE",
"image" : "MYIMAGE",
"likes" : 0
}]
EDIT
Thanks for the help this is now working!
json_decode expects an string, not an filename - so you have first get the contents of the given file. This could be easily achieved with file_get_contents.
Your current json structure contains an array(with currently only one element), which contains an object. So if you want the likes, you have to read the first element of the result array and of that(an associative array), the likes.
$data = json_decode(file_get_contents($filename), true);
$likes = $data[0]['likes'];
If you have more than one object in the given json file, you could loop over the data with foreach
foreach ($data as $element) {
echo "likes of {$element['title']}: {$element['likes']}\n";
}
For json_decode you have to pass JSON string, not a file name. Use file_get_contents to get JSON content and then decode it.
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]['likes'];
Your JSON is an array of objects, you first need to access the first element of your array :
$data[0]
Then you can access the key you want :
$getit = $data[0]['likes'];
Plus, as stated in a comment above, you need to pass a string to json encode, here is an code sample that should suit your needs :
<?php
$data = json_decode(file_get_contents('document.json'), true);
$getit = $data[0]["likes"];
Hope this helps.

Why json_decode() return empty?

I have this JSON string:
$json = '
{"id1":"x",
"N1":"x",
"T1":"x",
"E1":"x",
"E11":"x",
"O1":"x",
"C1":"x",
"C11":"x",
"F1":"x"},
{"id2":"x",
"N2":"x",
"T2":"x",
"E2":"x",
"E22":"x",
"O2":"x",
"C2":"x",
"C22":"x",
"F2":"x"}
';
and after I parse with PHP:
print_r(json_decode($json));
and you can see PHP return empty.
Any help, please...
Thanks
That's not really valid JSON syntax, if you intend that to be two objects, you need to put them in an array.
Like [
{your first object here},
{your next object}
]

How to Decode JSON object in Laravel

I want to decode gallery array JSON objects in Laravel 5.1. my JSON is:
{
"title": "aaaaaaaaaaaaaaaa",
"category_id": "1",
"user_id": "1",
"gallery": "[{name: \"XCB808tvXNpqXKqekA2HlkJ8H.jpg\",size:5112},{name: \"s6kA6B0e5m1sdSAjPXqNwtiy4.jpg\", size: 13135}]"
}
When I use this code, return me null:
public function store(Request $request)
{
$json = json_decode($request['gallery'],true);
return $json;
}
}
and this is dd($request['gallery']) result
[{'name': "XCB808tvXNpqXKqekA2HlkJ8H.jpg",'size':5112},{'name': "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", 'size': 13135}]
The decoding process is right. I think your problem is you could have a malformed JSON string.
Replace the single quotes around property names with double quotes:
[{"name": "XCB808tvXNpqXKqekA2HlkJ8H.jpg","size":5112},{"name": "s6kA6B0e5m1sdSAjPXqNwtiy4.jpg", "size": 13135}]
I am not pretty sure about your program flow but as you are injecting Request dependency to the store function, I assume the JSON object is a part of your request. In that case, you can try,
$input = $request->json()->all();
Just print_r($input) and see what you are getting.
If JSON object is not a part of your request, you missed passing $json to your function. This is a wild guess, though!
Just dropping by for having the same issue of trying to get the json formatted response (Laravel 8.8.0). The way I was able to get it working was using:
$jsonFormattedResult = json_decode ($response->content(), true);
Hope it helps someone out. ( '-')/
you can use Response::json($value);

getting value from json string php

$srt = '{"list":"[{"BP":"94"},{"BP":"99"},{"BP":"85"},{"BP":"84"},{"BP":"95"}]"}'
I want to decode this json object , in
$json_arr2 = array();
$json_arr2 = json_decode($srt,true);
var_dump($json_arr2);
It gives null, please help me to get value from this string in php.
The JSON isn't valid.
Try:
$srt = '{"list":[{"BP":"94"},{"BP":"99"},{"BP":"85"},{"BP":"84"},{"BP":"95"}]}';
http://www.jsonlint.com might help you in future.
Use http://www.jsoneditoronline.org/ to check how your json look like.
There should be no " before [ and after ]

how to use JSON.stringify and json_decode() properly

Im trying to pass a mulitidimensional Javascript array to another page on my site by:
using JSON.stringify on the array
assigning the resultant value to an input field
posting that field to the second page
using json_decode on the posted value
then var_dump to test
(echo'ing the posted variable directly just to see if it came through
at all)
Javascript on page one:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php on page two:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
The echo works fine but the var_dump returns NULL
What have I done wrong?
This got me fixed up:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
Figured it out using json_last_error() as sugested by Bart which returned JSON_ERROR_SYNTAX
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to #Thisguyhastwothumbs
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.
None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:
Javascript (added encodeURIComponent)
var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;
PHP (unchanged from the question)
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.
stripslashes(htmlspecialchars(JSON_DATA))
jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);`
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));

Categories