I'm trying to decode JSON format
What I am sending is:
{
"id": 123,
"name": "John",
“surname”: “Smith”,
“department”: 3
}
I am sending POST with data via Postman, in the picture.
So, this is the data I want to decode:
"data_serever_received": "{ \"id\": 123, \"name\": \"john\", “surname”: “Smith”, “department”: 3 }"
I tried
$this->input->data["id"]
but it is not working.
How can I get the id, name, surname and etc. values?
Your JSON is invalid “ and ” are not ".
(Zoom in with your browser if you can't see the difference).
You need to start with valid JSON before you can parse it.
You can use json_decode to make it an array.
$json_array = json_decode($json_object);//$json_object will need to contain your json string.
then you can access like this:
echo $json_array["data"][“surname”];
PHP Doc on json_decode: http://php.net/manual/en/function.json-decode.php
Related
I am able to send JSONObject data from my application to server with PHP. I am also able to read the data. But now I want to send the data with a USER ID and type of data in the first two sentences. I am able to send this data from my application.
But I am not experienced with working on PHP and I dont know how to split this data after reading USER id and the type I have received and to store the rest of data separately ( and should be stored as json data with USER ID as filename).
Currently I am using the following to just save the
<?php
$content = file_get_contents('php://input');
$data = json_decode($content, true);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
if(!is_array($data)){
throw new Exception('Received content contained invalid JSON!');
}
echo "Data Received";
?>
This is the json data format,
[{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
I also want to attach user id with it, which I am able to attach and send it to server, but I cannot use json decode now as the format changes to re encode if I give a userid with it in the first sentence . So after attaching userid and type the data looks like this
UserID Type [{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
What sentences? Send it where? Its far from clear what you are asking.
I dont know how to split this data
We don't either. What do you mean by split? That implies there's going to more than one data item - where do you want to split it? What do you want to do with the 2 parts?
should be stored as json data with USER ID as filename
It is very unlikely that it should be stored where you are currently putting it - particularly when you are applying no validation to the data you saved.
Consider (and note the differences with your script):
<?php
define("DEST_DIR", "/not/in/your/document/root/");
$content = file_get_contents('php://input');
$data = json_decode($content, true);
if (isset($data['USER'])) {
$filename=basename($data['USER']);
$filename="data_" . array_shift(explode('.', $filename) . 'json';
file_put_contents(DEST_DIR . $filename);
print json_encode(array('result'=>'success'));
} else {
header("Bad Request", true, 400);
print json_encode(array('result'=>'bad input data');
}
I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.
I want to decode json encoded data, My code output is
[ItemVariant] => [{"VariantID1":"36","VariantID2":"1","RevisionNumber":1,"LineNo":1},{"VariantID1":"47","VariantID2":"44","RevisionNumber":1,"LineNo":1}],
and i am using following code to decode it in controller file in save function
$variantdata = json_decode($this->request->data['ItemVariant']); ,
but not getting expected output,
please suggest me proper solution
There is a unrequired "," at the end. Please remove it.
This should help:
<?php
$str = '[
{
"VariantID1": "36",
"VariantID2": "1",
"RevisionNumber": 1,
"LineNo": 1
},
{
"VariantID1": "47",
"VariantID2": "44",
"RevisionNumber": 1,
"LineNo": 1
}
]';
$json = json_decode($str, true);
print_r($json);
?>
Run the code here:
http://codepad.org/GZcCdkd2
The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.
I've tried a variety of things, but still have not been able to return username from the output below. How would I do this? I ran this line below and got the string below:
$work = exec($cmd);
var_dump($work);
$json_object = json_decode($work, true);
string(1118) "{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T21:50:58-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}" "
echo:
{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T22:11:09-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}
var_dump:
string(1118) "{"user"=>{"id"=>4151878, "username"=>"jerry_smithjerry", "firstname"=>"Jerry ", "lastname"=>"Smith", "birthday"=>nil, "sex"=>0, "city"=>nil, "state"=>nil, "country"=>nil, "registration_date"=>"2013-07-24T16:12:20-04:00", "about"=>"", "domain"=>"jerry_smithjerry.500px.com", "fotomoto_on"=>false, "locale"=>"en", "show_nude"=>false, "fullname"=>"Jerry Smith", "userpic_url"=>"/graphics/userpic.png", "upgrade_status"=>0, "store_on"=>false, "email"=>"jerry_smithjerry#aol.com", "upload_limit"=>20, "upload_limit_expiry"=>"2013-07-24T22:11:09-04:00", "upgrade_type"=>0, "upgrade_status_expiry"=>nil, "auth"=>{"facebook"=>0, "twitter"=>0}, "contacts"=>{}, "equipment"=>{}, "photos_count"=>0, "affection"=>0, "in_favorites_count"=>0, "friends_count"=>0, "followers_count"=>0, "not_active"=>true, "avatars"=>{"default"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "large"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "small"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}, "tiny"=>{"http"=>"/graphics/userpic.png", "https"=>"/graphics/userpic.png"}}}}"
Your json string doesn't have valid json, the json strings uses : as a key value separator, in your case you have used a php associative array like => notation. This json is not valid json,
according to this: json_decode returns string type instead of object You may be running json_encode() on a json string. json_encode() is used if you want to turn an object or array into json.
If you are doing something like $work = json_encode($json_string) somewhere before that code, that would be the cause. remove that line, run json_decode() on your original json string and it should be fine.
Once you flesh that out, you can do
$json_object = json_decode($your_json_string);
echo $json_object->user->username; //echo's the username