Accessing data from API json response. Arrays? Laravel - json

I am trying to access the steamid data in a json response returned by an API, specifically the Steam API.
The responses look like this:
I've made it return json but why do I see array all over the place?
How would I access the steamid data? I'm getting a bit confused as I thought this would be json.
I'm using guzzle to get the data and converting it to json using the guzzle json() method:
Any help would be appreciated.
Thanks!

The API is indeed using JSON to send/receive , however JSON is just a string, so in order to use that data PHP must parse it, which is automatically handled by guzzle, so as soon as you get the data back it has automatically decoded the data into a usable format for yourself.
It does this using the json_encode() and json_decode() functions.
You'd be able to access the steamid with the following.
// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);
foreach($players as $player)
{
$steamId = array_get($player, 'steamid', null);
}
Using the laravel helper array_get() function is a great way of ensuring you return a sane default if the data doesn't exist as well as eliminating the need to keep doing things like isset() to avoid errors about undefined indexes, etc. http://laravel.com/docs/5.1/helpers
Alternativly not using the laravel helpers you could use something similar to below, although I'd advise you add checks to avoid the aforementioned problems.
foreach($data['response']['players'] as $player)
{
$steamId = $player['steamid'];
}
If you didn't want guzzle to automatically decode the API's JSON I believe you should just be able to call the getBody() method to return the JSON string.
$json = $response->getBody();

Related

how to parse dynamic json object in Typescript

I have a json object in my typescript which is returned from server side. One of the keys is dynamic. How do I parse and extract the value for that key.
Ex: serverResponse.detailsLMN.allList
Ex :serverResponse.detailsLMN.deleteList
In the above , 'LMN' is dynamic.
It can be serverResponse.detailsLMN.allList or serverResponse.detailsPQR.allList.
Assuming,
const temp = 'LMN' or 'PQR', how can I use temp to parse JSON object here.
Like : serverResponse.details{temp}.allList
Not sure if I understood your question correctly. But try doing
let data = JSON.parse(serverResponse);
((JSON.stringify(serverResponse)).includes("LMN")) ? serverResponse.detailsLMN.allList
: serverResponse.detailsPQR.allList
^The above code is the same as the if statement. If you don't know the ES6 ternary conditional statement then here's a link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
To parse, simply use JSON.parse(). To extract the value, since I can't see the format of the output, it's better to console.log(serverResponse) the whole response and then walk through the Object in Chrome console to see how to get to your specific value.

MongoDB not returning a proper JSON

When I run db.collection.explain().find(), it gives the following error;
The last field in this json object has a double quote problem: `"totalChildMillis" : NumberLong(2)`.
When I parse this object, I got an exception saying that NumberLong(2) should be double quoted. Is there a way for MongoDB returns a standard JSON object?
{
"executionStages":{
"stage": "SINGLE_SHARD",
"nReturned": 10000,
"executionTimeMillis": 3,
"totalKeysExamined": 0,
"totalDocsExamined": 10000,
"totalChildMillis": NumberLong(2)
}
}
EDIT1
I am currently using Javascript NodeJS to create a sub-process of a mongo-shell. And send explain command to that process and listen on its output. Once I got the output, I need to parse it to a javascript object by JSON.parse() method. Based on this use case, what is the easier way for me to adapt mongo json extension to be a standard javascript object?
See the docs on MongoDB Extended JSON. Basically it comes down to the fact that MongoDB extends JSON to add additional datatypes that JSON does not support. In order to preserve that type information, various tools use either "strict" mode (which confirms to the JSON RFC) or "mongo shell" mode, which uses notations like NumberLong() and ISODate() to represent datatypes and is generally not parseable using a JSON parser.
Depending on what you're doing, you can use mongoexport which has an option to output in strict mode. But if you're trying to evaluate the explain plan of a query, I don't think that's going to work unless you insert the explain plan into a temp collection and then mongoexport it out.
Your best bet is to do whatever scripting you're trying to accomplish using a programming language (e.g. Java, Perl, Python, C#, etc.) and one of the corresponding MongoDB drivers. There you'll have much more flexibility and power with how you retrieve and parse data.
Since you mentioned in your edit that you're using Node.js, you can use the explain option to get the explain output directly from Node without having to spawn a sub-process.
Here's a very basic example:
var url = 'mongodb://localhost:27017/test';
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var collection = db.collection('test');
collection.find({}, {explain:true}).each(function(err, doc) {
if(doc != null)
console.dir(doc);
});
});

ZF2: What's the easiest way to return a boolean json response?

In ZF1 it was pretty easy to send a json boolean response, for example, in the controller use:
return $this->_helper->json(true);
What's the easiest way to repeat this in ZF2?
I tried creating a new JsonModel with an array of variables. The only entry in the array was my boolean value (with a key of 0). This didn't work because the resolver was still off looking for a template.
I think I somehow need to return early?
EDIT:
I think this is a really important issue. For example, when the JQ Validation plugin uses a server-side validation method, it expects a JSON boolean response.
I managed to make my application JSON-ready by following 'alternate rendering and response strategies' section at the bottom of the Zend\View page, http://framework.zend.com/manual/2.0/en/modules/zend.view.quick-start.html. But this operates on the array that has been passed to the view, so the boolean true becomes json [true]
I tried the json view helper in various combinations, but couldn't get it to work.
Perhaps I need to create my own rendering and response strategies? That seems like overkill though...
Rob Allen has written an article about it:
Returning JSON from a ZF2 controller action
Also you can try this code to return every data without view rendering:
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent('some data');
return $response;
The easiest way:
echo "true";
exit;
Though you may want to output some appropriate headers.
Arguably the correct way would be to add the JsonStrategy as viewstrategy and use a JsonModel, but I think it always returns an object (the json_encoded associative array of view variables passed to the JsonModel).

Wrapping JSON payload with key in EmberJS

Ok basically I am sending a POST request with some JSON payload in it to Codeigniter. I use RESTAdapater. JSON get sent there with no key, so I have no access to it.
Here is model:
App.Bookmark = DS.Model.extend({
title: DS.attr("string"),
url : DS.attr("string")
});
Here is controller:
App.BookmarksNewController = Ember.ObjectController.extend({
save: function(){
this.get("model.transaction").commit();
this.get("target").transitionTo("bookmarks");
}
});
In REST implementation in CI that I use standard way to access the post request is $this->input("key"). But when the above request is generated, only raw JSON data is sent. Therefore I don't seem to have a way to reference it in any way.
Take this example:
function post(){
$this->response(var_dump(file_get_contents("php://input")),200);
}
Gives me this output:
string(48) "{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
what I would like to see is:
string(48) payload="{"bookmark":{"title":"sdffdfsd","url":"sdfsdf"}}"
Then is server I would be able to access this JSON with something like $this->post("payload").
So 1 of 2. Anyway to wrap the JSON payload with key? Or anyway to access raw JSON data in CI with no key available??
Ok figured it out myself (or rather read properly the examples).
When using Adam Whitney's fork of Phil Sturgeons REST controller for CodeIgniter the JSON payload will be available in $this->_post_args. And in the underlying implementation he uses my already mentioned file_get_contents("php://input").
EDIT: Same convention applies for other type of requests as well, for example DELETE request data will be available in $this->_delete_args. Or $this->_args is the "magic" place where all types of args can be found.

Confused with JSON data and normal data in Django ajax request

I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
From where the function is getting format variable
Does format is json mean that data given to function is json or data which will be recived is json
Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all())
How will I use that data when i get that response in jquery function
If i don't use JSON in above function then how will the input and response back will chnage
Thanks
From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept: header that requests can use to indicate the preferred Content-Type for the response. On the client, you might use xhr.setRequestHeader('accept', 'application/json') to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending on how complicated your request needs to be, you can use jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can use jQuery.parseJSON to process the json data, and that will return the same JavaScript objects.
From the urlconf, just like it says in the article right below it.
The query set will be serialized as JSON.
It will be the query set represented as either XML or JSON. python manage.py shell is your friend.
You will decode it, then iterate over it.
You'll need to find some other format to serialize it in instead.