I made an API call (google translate) and it returns the following:
{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.051902372
}
]
]
}
}
I want to access the "language" value using javascript (using the jQuery ajax function). I tried something like:
response.data.detections[0][0].language
but that does not work. Help?
We really do need more information but if I had to guess blindly I would guess that response actually contains the following string:
'{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.051902372
}
]
]
}
}'
If that is the case you could try something like $.parseJSON(response).data.detections[0][0].language
Related
The server I'm working with changed the REST format from plain JSON:
{
"removedVertices": [
{
"id": "1",
"info": {
"host": "myhost",
"port": "1111"
},
"name": "Roy",
"type": "Worker"
}
],
"id": "2",
"time": 1481183401573
}
To Jackson format:
{
"removedVertices": [
"java.util.ArrayList",
[
{
"id": "1",
"info": [
"java.util.HashMap",
{
"host": "myhost",
"port": "1111"
}
]
"name": "Roy",
"type": "Worker",
}
]
"id": "2",
"time": 1482392323858
}
How can I parse it the way it was before in Angular/Javascript?
Assuming only arrays are affected, I would use underscore.js and write a recursive function to remove the Jackson type.
function jackson2json(input) {
return _.mapObject(input, function(val, key) {
if (_.isArray(val) && val.length > 1) {
// discard the Jackson type and keep the 2nd element of the array
return val[1];
}
else if (_.isObject(val)) {
// apply the transformation recursively
return jackson2json(val);
}
else {
// keep the value unchanged (i.e. primitive types)
return val;
}
});
}
If the api should be restful, then the server should not return none plain json results. I think the server site need to fix that.
I think it is because the server enabled the Polymorphic Type Handling feature.
Read Jackson Default Typing for object containing a field of Map and JacksonPolymorphicDeserialization.
Disable the feature and you will get result identical to plain json.
The main difference i see is that in arrays you have an additional string element at index 0.
If you always get the same structure you can do like this:
function jacksonToJson(jackson) {
jackson.removedVertices.splice(0, 1);
jackson.removedVertices.forEach((rmVert) => {
rmVert.info.splice(0, 1);
});
return jackson;
}
I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.
I have this short json from an AJAX call that execute a SPARQL query:
{
"head": {
"vars": [ "name" , "email" ]
} ,
"results": {
"bindings": [
{
"name": { "type": "literal" , "value": "Name Surname" } ,
"email": { "type": "literal" , "value": "name.surname#email.com" }
}
]
}
}
I'm searching name and email of a single user of the application, so
the result should be always made up of a single element.
What I want to retrieve is the "name" of the user.
I tried something like:
response["name"].value
//or
response[0]["name"]
//or
response.name
but always wrong.
How can I get the name value? Thanks to everyone who will help.
Try this
response.results.bindings[0].name.value
response.results.bindings[0].email.value
Update
Example
You can check out the fiddle created here
http://jsfiddle.net/uqxp4j73/
The code for this is as under
var x='{ "head": { "vars": [ "name" , "email" ] } , "results": { "bindings": [ { "name": { "type": "literal" , "value": "aadil keshwani" } , "email": { "type": "literal" , "value": "name.surname#email.com" } } ] }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);
Hope this helps :)
In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.
response.results.bindings[0].name.value for name
response.results.bindings[0].email.value for email
Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.
I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.
I'm using REST adapter, when I call App.Message.find() Ember.js makes call to the /messages to retrieve all messages and expect to see JSON structure like this:
{
"messages": [] // array contains objects
}
However API I have to work with response always with:
{
"data": [] // array contains objects
}
I only found the way1 to change namespace or URL for the API. How to tell REST adapter to look for data instead of messages property?
If this is not possible how to solve this problem? CTO said we can adapt API to use with REST adapter as we want, but from some reason we can't change this data property which will be on each response.
Assuming you are ok with writing your own adapter to deal with the difference, in the success callback you can simply modify the incoming name from "data" to your specific entity -in the case above "messages"
I do something like this to give you and idea of what if possible in a custom adapter
In the link below I highlighted the return line from my findMany
The json coming back from my REST api looks like
[
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
I need to transform this before ember-data gets it to look like this
{
"sessions": [
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
}
https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js#L56-57
findMany: function(store, type, ids, parent) {
var json = {}
, adapter = this
, root = this.rootForType(type)
, plural = this.pluralize(root)
, ids = this.serializeIds(ids)
, url = this.buildFindManyUrlWithParent(store, type, ids, parent);
return this.ajax(url, "GET", {
data: {ids: ids}
}).then(function(pre_json) {
json[plural] = pre_json; //change the JSON before ember-data gets it
adapter.didFindMany(store, type, json);
}).then(null, rejectionHandler);
},
I aam trying to GET an array from a JSON file using JQuery's ajax methods. Specifically, I want to make the ajax request on document load and use the acquired data in other functions.
Here is my code:
$(document).ready(function() {
getJSON();
clickEvents();
});
function getJSON() {
$.getJSON('goods.js', function(data) {
crazyFun(data.Goods);
addScores(data.karma);
});
}
}
function addScores(karma) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
function crazyFun(Goods) {
for (var i = 0; i < Goods.length; i++) {
var alpha= $('#template').clone();
alpha.removeAttr('id');
alpha.find('div.picture').attr('id', Goods[i].picture);
alpha.find('h2').html(Goods[i].header);
alpha.find('p').html(Goods[i].text);
alpha.find('div.notification').attr('id', Goods[i].notification);
$('#repeater').append(alpha);
}
}
karma and Goods are the name of the arrays in the JSON file.
What am I doing wrong?
Here is my JSON array for karma:
{
Goods : [{
"header": "Apple",
"text": "hi"
"picture": "appleImage",
"notification": "appleNote"
}, {
"header": "Pear",
"text": "hi",
"picture": "pearImage",
"notification": "pearNote"
}, {
"header":hi",
"picture": "bananaImage",
"notification": "bananaNote"
}, {
"header": "Dog",
"text": "hi",
"picture": "dogImage",
"notification": "dogNote"
}, {
"header": "Cat",
"text": "hi",
"picture": "catImage",
"notification": "catNote"
}, {
"header": "Snake",
"text": "hi",
"picture": "snakeImage",
"notification": "snakeNote"
}],
karma : [{
"karmaYinYangScore": "200",
"KarmaGiveScore": "40",
"KarmaTakeScore": "99",
"ItemsGiveScore": "20",
"ItemsTakeScore": "77"
}];
}
I can only guess what your data looks like, but since you said "karma and Goods are the name of the arrays", I'm going to assume we're talking about something like this:
{
karma: [{
karmaYinYangScore:'some value',
KarmaGiveScore:'some value',
KarmaTakeScore:'some value',
ItemsGiveScore:'some value',
ItemsTakeScore:'some value'
}
],
Goods: ['more','array','values']
}
If that's the case, we've got a few issues in your code.
First, getJSON returns one data result, so you should be referencing only that data returned.
function getJSON() {
$.getJSON('goods.js', function( data ) {
crazyFun( data.Goods ); // reference Goods array from data response
addScores( data.karma ); // reference karma array from data response
});
}
Then, your .addScores() function doesn't accept a parameter. You need some reference to receive the array being passed.
// Reference to the array being passed to the function
// ---------------v
function addScores( karma ) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
These are the only errors I see. Beyond that, the solution depends on the actual data structure of the response.
According to jQuery's documentation on the getJSON function (http://api.jquery.com/jQuery.getJSON/), your callback's parameters appear to be misleading. Your callback...
function(Goods, karma) {
crazyFun(Goods);
addScores(karma);
}
...appears to be expecting the arrays of data to be passed to it automatically, but jQuery actually passes the whole JSON result as the first parameter, and the status of your request as the second parameter, regardless of how the JSON is structured. Your callback should probably look more like this:
function(json, status) {
crazyFun(json.Goods);
addScores(json.karma);
}
This assumes that your JSON is well formed, and that the "Goods" and "karma" properties are properties of the root object. You may need to modify the callback if your JSON is structured differently.