I have this json but I have no idea how to get 7796249#N02
a:2:{s:4:"user";a:3:{s:2:"id";s:11:"7796249#N02";s:4:"nsid";s:11:"7796249#N02";s:8:"username";a:1:{s:8:"_content";s:9:"ilhan.z.y";}}s:4:"stat";s:2:"ok";}
That is a serialized PHP array, not JSON. Use:
$array = unserialize('that response goes in here');
What language are you using? In Groovy, for example, you would do something like this:
import groovyx.net.http.*
#Grab(group='org.codehaus.groovy.modules.http-builder',
module='http-builder', version='0.5.0' )
def http = new HTTPBuilder( 'http://twitter.com/statuses/' )
http.get( path: 'user_timeline.json',
query: [id:'httpbuilder', count:5] ) { resp, json ->
println resp.status
json.each { // iterate over JSON 'status' object in the response:
println it.created_at
println ' ' + it.text
}
}
Edit after PHP tag added:
I'm not a PHP guy, but it looks like json_decode is what you need to use.
Related
I am using the same code within two PHP- classes. I copied and pasted it.
In one class an Array is delivered to the JavaScript in which I use a copied/pasted piece of code, too and once an Object.
Here is the PHP- Code:
private $status_good = array('Status' => 'good');
private $status_fail = array('Status' => 'fail');
echo json_encode($this->status_fail);
And here is the JS/jquery- Code:
$.post("./someclass.php",
{
code : this.code,
input : this.input
},
function( data ){
console.log("Data: ")
console.log(data );
}
Once the console says: Data: {"Status":"fail"}
In the other script: Data: Object { Status: "fail" }
I am doing no UTF- manipulation nor any header- manipulation.
Please be so kind and tell me how this may happen with exactly the same code in different classes.
Thanks in advance.
Add the dataType argument to $.post and/or set Content-type header in the php.
$.ajax does a "best guess" at the data type being returned if it is not explicitly told what to expect and there is no header to help it decide.
It would appear that it is getting it right in the one case and parsing JSON and in the other it is treating it as text and returning a string to the callback.
$.post("./someclass.php",
{
code : this.code,
input : this.input
},
function( data ){
console.log("Data: ")
console.log(data );
},'json')
I am trying to have a python client send a post request which contains nested JSON like such
{"nested":{"field1":"response1", "field2":"response2"}}
My python code is here
from urllib.parse import urlencode
from urllib.request import Request, urlopen
url="http://localhost/api/vscore.php"
post_fields={"nested":{"field1":"response1", "field2":"response2"}}
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
PHP code:
print_r($_POST["nested"]);
returns
{'field2': 'response2', 'field1': 'response1'}
but when I try to access "field1" with $_POST["nested"]["field1"], it returns this:
{
instead of returning "response1". How can I get my code to return fields in nested JSON?
If request is in json form then, you should json_decode it first and then try to access. nested key should be accessed as:
$nested = json_decode($_POST["nested"], true);
$field = $nested["field1"];
Output when success
string(66)
"{"status":true,"message":"success","data":{"amountDue":"-504.20"}}"
Output when error
string(119) "{"status":false,"message":"An error occured while getting
full subscriber profile: Subscription not found MPP servers"}"
How should I write in php to get the amount due from the output? I am new to REST api. Can someone show me ? Thank you
That is a JSON-encoded response. Use json_decode() to convert the string back into an array, and then access the array element:
$output = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$results = json_decode($output,true);
if($results["status"])
{
echo "Success! Data: " . print_r($results,true);
}
I assume that you can at least send proper request to the endpoint and you are able to capture the response.
You receive a json string which must be parses so if:
$response = '{"status":true,"message":"success","data":{"amountDue":"-504.20"}}';
$responseArray = json_decode($response, true);
Then you will get a responseArray as associated array (the second parameter) so you can get amount due like that
$amountDue = $responseArray['data']['amountDue'];
You could also parse json data into an StdClass which turn all fields in json into an object's property. To do that abandon the second parameter in json_decode function
$resultObj = json_decode($response);
$amountDue = $resultObj->data['amountDue'];
All depends on your requests.
To read more about json_decode try documentation
I have an some PHP that looks like this:
$exec[0] = shell_exec("cat /etc/msm.conf | grep JAR_PATH");
$exec[1] = shell_exec("msm server list");
if(strstr($exec[1],'[ ACTIVE ] "mc-srv" is running. Everything is OK.') !== FALSE){
$exec[1] = 'mc online';
}else{
$exec[1] = 'mc offline';
}
$exec[2] = shell_exec("sudo ts status");
if($exec[2] == 'Server is running'){
$exec[2] = 'ts online';
}else{
$exec[2] = 'ts ofline';
}
echo json_encode($exec,JSON_FORCE_OBJECT);
An AJAX request gets sent to the page and the json is returned.
If I use console.log(JSON.parse(data)) I see this in the console Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"} however I can not access any of its methods even if i use an associative array.
but If i create a new object and print that to the console it (in chrome atleast) looks exactly the same in terms of syntax highlighting exect I can access it via obj.method.
What am I doing wrong here?
Based on how the object is being output in the console, it looks like it's being parsed okay by JSON.parse and is valid.
In which case, you should be able to access each method like this:
var obj = JSON.parse(data);
console.log( obj['0'] ); // returns "DEFAULT_JAR_PATH="server.jar""
console.log( obj['1'] ); // returns "mc online"
obj.0 won't work in this case because the method names are numbers.
I am using AFJSONRequestOperation to request a server and parse the returned JSON response, but while parsing, I got this error:
NSDebugDescription = "JSON text did not start with array or object and option to allow fragments not set.";
I checked the API and it's returning JSON data:
header('Content-type: text/json');
$arr[] = array("Message" => "update succeeded");
echo '{"Result":'.json_encode($arr).'}';
Any idea how to fix that?
EDIT
I tried to call the API from browser and include the request in the url, and so I got a valid JSON response:
{"Result":[{"Message":"update succeeded"}]}
First thing, json_encode the entire object rather than breaking into it pieces.
Secondly, unless $arr contains multiple elements (not clear from example above), it should be initalized as thus:
$arr = array("Message" => "update succeeded");
I'm still not certain what else could be the issue here. You should echo out what your app is receiving and that should indicate the issue.
Please use acceptable content type.
in your webservice that should be only plain text.
here is my swift code and fixed:
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer=AFJSONRequestSerializer()
manager.responseSerializer = AFHTTPResponseSerializer();
manager.GET(
baseURL + (webServiceType as String) + secureParam,
parameters:[:],
success:
{ (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
completion(obj: responseObject)
},
failure:
{ (operation: AFHTTPRequestOperation!,
error: NSError!) in
completion(obj: nil)
})
Check you have added /api/ before your base url of API like
http:// someurl / yourBasrUrl /api/apiName
To make a valid json response, your code should
look something like this:
$response = array(
"Result" => array(
"Message" => "update succeeded"
)
)
echo json_encode($response);
If you need read fragment json you can use option .allowFragments like this:
JSONSerialization.jsonObject(with: someData, options: .allowFragments)
Please try this:
let manager = AFHTTPSessionManager(baseURL: NSURL("Base URL"))
manager.requestSerializer = AFJSONRequestSerializer()
manager.responseSerializer = AFJSONResponseSerializer()
let params = [
"foo": "bar"
]
manager.POST("API url", parameters: params,
success: {
(task: NSURLSessionDataTask!, responseObject: AnyObject!) in
print("success")
},
failure: {
(task: NSURLSessionDataTask!, error: NSError!) in
print("error")
})
First of all, your API is returning improper Content-Type. Proper content type for JSON data is application/json. This may be conflicting while using third-party libraries.
Secondary, you should not produce json string "by hand". Altogether API should be modified to face:
header('Content-type: application/json');
$arr[] = array("Message" => "update succeeded");
echo json_encode(array('Result' => $arr));
Last bat not least. There is one more thing in charge possible: you might have BOM characters at very beginning of your api PHP script. Those are whitespace, so you may not see them in browser. Please, ensure that your PHP files are encoded without BOM.