How do I parse a JSON object in PHP? - php

I've got a JSON object that I'm sending to a PHP script and I'm having trouble parsing the JSON. Here's the POST request:
http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}
And here's my PHP function, which obviously doesn't work:
$data = $_GET['data'];
$obj = json_decode($data);
echo $obj->Name;
die();
The end goal is to extract the name "Mike" from the URL string. Any suggestions?

Try taking a look at what PHP is outputting from json_decode():
$data = $_GET['data'];
$obj = json_decode($data);
var_dump($obj);
Your code itself works fine: http://ideone.com/0jsjgT
But your query string is missing the data= before the actual JSON. This:
http://mywebsite.com?action=somefunction&{%22id%22:1,%22Name%22:%22Mike%22}
should be this:
http://mywebsite.com?action=somefunction&data={%22id%22:1,%22Name%22:%22Mike%22}

you should do
echo $obj->{'Name'};
This also is a duplicate question of Echo data json by json_decode

Related

Get values from JSON array using PHP

I run the following PHP after I submit a form and get the output shown below:
$data = json_encode($_POST);
// output
{"First_Name":"Fred"}
How do I use PHP to just display the value 'Fred'?
I tried echo $data['First_Name']; but this is blank.
You no need to encode your incoming $_POST data.
Just say:
echo $_POST['First_Name'];
If you get a json data, decode it into an array:
$data = '{"First_Name":"Fred"}';
$decoded = json_decode($data, true);
echo $decoded['First_name'];
First of all, don't know why you use json_encode on PHP Array, and try to access it like it's an array - because after json_encode it's a string.
You have to use json_decode($data, true) and then you can access it like $data['First_Name'] or try to access it directly without json_encode() by $_POST['First_Name']
The json_decode() function is used to decode or convert a JSON object to a PHP object.And try to put the object to decode in another variable to avoid errors
<?php
$obj = '{"First_Name":"Fred"}';
$data = json_decode($obj);
echo ($data->First_Name);
?>

Decode php://input json

I have this text from file_get_contents('php://input'):
[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]
I need to get single element like email or event, but haven't been able to get json_decode and others to work.
$obj = json_decode(file_get_contents('php://input'));
How can I reference a single element in the json data?
You have an array, so, you need to get the first element:
$json = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($json);
echo $obj[0]->email; //output text#examlple.com
Here you go, here's a fully working answer:
<?php
$str = '[{"email":"text#examlple.com","event":"processed","sg_event_id":"JJTr9qA","sg_message_id":"AjvX5L7IQeGOfxmJV-OCnw","smtp-id":"<AfxmJV-OCnw#ismon1.sendgrid.net>","timestamp":16813363}]';
$obj = json_decode($str);
echo $obj[0]->email;

How do I "trim" this JSON with PHP?

I have a JSON that's strangely formatted ...but it's the way I receive it. Because the arrays inside are huge, simply copying and pasting it takes a long time, so I'm wondering if there's a PHP way to do it.
The way I get it is like this:
{"count":459,"results":[{"title":"Something ....}],"params":{"limit..},"type":"Listing","pagination":{"..":5}}
But I want to get only the "results" array, basically the part of [{"title":"Something ....}]. How would I do that?
Do
$arr = json_decode(your_json, true);
If you ned it as JSON again, do
json_encode($arr['results']);
You can get to that part as follows:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit":".."},"type":"Listing","pagination":{"..":5}}';
$obj = json_decode($json);
echo $obj->results[0]->title;
Outputs:
Something ....
You have to decode your json. Be sure that the json is valid!
Your decoded json returns an object of type stdClass instead of an array!
See below the tested code:
$json = '{"count":459,"results":[{"title":"Something ...."}],"params":{"limit": "foo"},"type":"Listing","pagination":{"foo":5}}';
$decoded = json_decode($json);
So you can access array results from the object $decoded:
print_r($decoded->results);
But, in the array, there are objects, thus:
echo $decoded->results[0]->title; // Something ....

Decode json data from .json file in php

I am trying to output some json data from a json file via php but it does not seem to work. I tried this:
<?php
$jsonFile = file_get_contents('dataset/dataset.json');
$data = json_decode($jsonFile, true);
echo $data->{'data'}[0]->{'letter'}
?>
The json file is following:
{
"data":[
{
"letter":"A",
"blocks":{
"1":"0",
"2":"0",
"3":"0",
"4":"0",
"5":"0"
}
}
]}
Basically it should output the letter "A" but it outputs nothing. What did I do wrong?
Thanks
P.S. I tried to do it like here: How to process JSON in PHP? but it does not work.
After json_decode($jsonFile, true) your data is in array. So you should not access using object. Access data by array index. Try this..
echo $data['data'][0]['letter'];
More about json_decode()
This says, you get an array (the true parameter):
$data = json_decode($jsonFile, true);
You can see this if you do this:
print_r($data);
Try this:
echo $data['data'][0]['letter'];

Reading multiple json values with php

I am trying to read certain values from a json string in php, I am able to do a simple json string with only one value such as
$json = '{"value":"somevalue"}';
Using this:
<?php
$json = '{"value":"somevalue"}';
$obj = json_decode(json_encode($json));
print $obj->{'value'};
?>
But when i try an get a value from the following json string it throws an error...
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
I validated the json on JSONlint but not sure how to access the values within this with php.
Thanks
You can try this:
$json = '{"field": "title","rule": {"required": "true","minlength": "4","maxlength": "150" }}';
//since $json is a valid json format you needn't encode and decode it again
$obj = json_decode($json);
print_r($obj->filed);
print_r($obj->rule);
You can pass true as a second parameter to json_decode() to get the results as an array
$my_arr = json_decode($json, true);
var_dump($my_arr);
Should help you. You can then step through the array as you would normally.
use var_dump to print out the object with all it's members and hierarchy. you should then be able to find the value you are looking for

Categories