I have this JSON response i need to get the values of some elements inside this response.
The values i want to display is the value of "makeup" which has to elements in it which are, "eyemakeup" & "lipmakeup"
i want to display it in an alert / or textbox.
[
{
"faceId": "90c30c46-2a51-4754-bff4-5079caf7e322",
"faceRectangle": {
"top": 91,
"left": 101,
"width": 121,
"height": 121
},
"faceAttributes": {
"smile": 0,
"headPose": {
"pitch": 0,
"roll": -0.8,
"yaw": -2.3
},
"gender": "male",
"age": 30.3,
"facialHair": {
"moustache": 0.1,
"beard": 0.5,
"sideburns": 0.3
},
"glasses": "NoGlasses",
"emotion": {
"anger": 0.013,
"contempt": 0.003,
"disgust": 0,
"fear": 0,
"happiness": 0,
"neutral": 0.983,
"sadness": 0.001,
"surprise": 0
},
"blur": {
"blurLevel": "medium",
"value": 0.28
},
"exposure": {
"exposureLevel": "goodExposure",
"value": 0.61
},
"noise": {
"noiseLevel": "medium",
"value": 0.39
},
"makeup": {
"eyeMakeup": false,
"lipMakeup": true
},
"accessories": [],
"occlusion": {
"foreheadOccluded": false,
"eyeOccluded": false,
"mouthOccluded": false
},
"hair": {
"bald": 0.02,
"invisible": false,
"hairColor": [
{
"color": "brown",
"confidence": 1
},
{
"color": "black",
"confidence": 0.78
},
{
"color": "blond",
"confidence": 0.23
},
{
"color": "other",
"confidence": 0.13
},
{
"color": "red",
"confidence": 0.09
},
{
"color": "gray",
"confidence": 0.03
}
]
}
}
}
]
The below is the javascript i have used so far and it is not giving me the correct values.
<script type="text/javascript">
function processImage() {
var subscriptionKey = "mysubkey";
var uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
// Request parameters.
var params = {
"returnFaceId": "true",
"returnFaceLandmarks": "false",
"returnFaceAttributes": "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
};
// Display the image.
var sourceImageUrl = document.getElementById("inputImage").value;
document.querySelector("#sourceImage").src = sourceImageUrl;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: '{"url": ' + '"' + sourceImageUrl + '"}',
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
$("#demo2").val(this.responseText);
var data =[JSON.stringify(data, null, 2)];
var json = JSON.parse(data);
alert(json["eyeMakeup"]);
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ? "Error. " : errorThrown + "
(" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};
</script>
First add contentType:"json" your $.ajax configuration,
Then you don't need to parse data to json since it's already json type
So remove this line.
var data =[JSON.stringify(data, null, 2)];
As per your json you added to question you receive a array of object
To get data from first object
Try this :
For eyeMakeup use :
data[0].faceAttributes.makeup.eyeMakeup
and for lipMakeup use
data[0].faceAttributes.makeup.lipMakeup
Or you can loop through your result data if you want to access multiple object data
$.each(data,function(obj,function(){
console.log(obj.faceAttributes.makeup.eyeMakeup);
console.log(obj.faceAttributes.makeup.lipMakeup);
})
$.ajax( {
url:'data.php',
data:{
'a' : 1,
'b': 2
},
type:'post',
cache:false,
dataType:'json',
success:function(data) {
do something...
},
error : function() {
do something
}
});
try use ajax like up above
Related
I'm trying to make a auto complete search bar using jquery autocomplete. The thing is I need to display Json data from an external site into my search bar.
Whenever I try to put the data as such from json into the script, it's working. But when I refer external url it refuses to work.
I tried implementing all json data into my script. But it takes so long to process as there will be more than 40000+ lines in my html page.
The Json link for the data which I have to display is here
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": [
{
"symbol": "AACG",
"name": "ATA Creativity Global American Depositary Shares",
"lastsale": "$2.19",
"netchange": "-0.45",
"pctchange": "-17.045%",
"volume": "1408435",
"marketCap": "68715455.00",
"country": "China",
"ipoyear": "",
"industry": "Service to the Health Industry",
"sector": "Miscellaneous",
"url": "/market-activity/stocks/aacg"
},
{
"symbol": "AACI",
"name": "Armada Acquisition Corp. I Common Stock",
"lastsale": "$9.88",
"netchange": "0.01",
"pctchange": "0.101%",
"volume": "8345",
"marketCap": "204609860.00",
"country": "United States",
"ipoyear": "2021",
"industry": "",
"sector": "",
"url": "/market-activity/stocks/aaci"
}],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
The above code works and the below code doesn't.
<script>
$('#id_ticker').autocomplete({
source: function(request, response) {
var data = {
"success": true,
"data": ["https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json"
],
"additional_data": {
"pagination": {
"start": 0,
"limit": 5,
"more_items_in_collection": true,
"next_start": 5
}
}
};
var datamap = data.data.map(function(i) {
return {
label: i.symbol + ' - ' + i.name.split(' ').slice(0, 2).join(' '),
value: i.symbol,
desc: i.title
}
});
var key = request.term;
datamap = datamap.filter(function(i) {
return i.label.toLowerCase().indexOf(key.toLowerCase()) >= 0;
});
response(datamap);
},
minLength: 1,
delay: 500
});
</script>
Looking for a solution to add this and also for a solution to reduce the json key pair with only "symbol" and "name" from each corresponding data in the link.
Try this:
function toAutocomplete(dt, keyvar){
let rli = [];
for (let i = 0; i < dt.length; i++) rli.push(dt[i][keyvar]);
return rli;
}
function inArrayAutocompleteSelected(key, array_autocomplete, array_master){
let x = array_master[$.inArray(key, array_autocomplete)];
return x;
}
$('#id_ticker').autocomplete({ source: [], minLength: 1 });
// $('#id_ticker').autocomplete("disable");
let url = 'https://raw.githubusercontent.com/rreichel3/US-Stock-Symbols/main/nyse/nyse_full_tickers.json';
let r = _ajax('GET', url, ''); // your ajax script
console.log(r);
let liAuto = toAutocomplete(r, 'name');
console.log(liAuto);
$('#id_ticker').autocomplete("option", "source", liAuto );
// $('#id_ticker').autocomplete("enable");
$("#id_ticker").autocomplete({
select: function( event, ui ) {
console.log(ui, ui.item);
getData = inArrayAutocompleteSelected(ui.item.value, liAuto, r);
console.log(getData);
}
});
I have a JSON response that shows like this:
{
"gameId": 2540832082,
"mapId": 12,
"gameMode": "ARAM",
"gameType": "MATCHED_GAME",
"gameQueueConfigId": 65,
"participants": [
{
"teamId": 100,
"spell1Id": 32,
"spell2Id": 7,
"championId": 25,
"profileIconId": 774,
"summonerName": "MLG Elan",
"bot": false,
"summonerId": 77477471,
"runes": [],
"masteries": [
{
"rank": 5,
"masteryId": 6111
},
{
"rank": 1,
"masteryId": 6122
},
{
"rank": 2,
"masteryId": 6131
}
]
},
{
"teamId": 100,
"spell1Id": 4,
"spell2Id": 32,
"championId": 120,
"profileIconId": 774,
"summonerName": "Nuetzlich",
"bot": false,
"summonerId": 43800105,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 3,
"masteryId": 6114
},
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6322
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 5,
"masteryId": 6351
},
{
"rank": 1,
"masteryId": 6362
}
]
},
{
"teamId": 100,
"spell1Id": 13,
"spell2Id": 7,
"championId": 67,
"profileIconId": 19,
"summonerName": "SonicmoĆgrel",
"bot": false,
"summonerId": 82267777,
"runes": [
{
"count": 6,
"runeId": 5245
},
{
"count": 2,
"runeId": 5335
}
],
"masteries": [
{
"rank": 5,
"masteryId": 6312
},
{
"rank": 1,
"masteryId": 6323
},
{
"rank": 5,
"masteryId": 6331
},
{
"rank": 1,
"masteryId": 6343
},
{
"rank": 4,
"masteryId": 6351
}
]
},
I'm struggling to get the "summonerNames" for each player and display them on the site :(
What jQuery do I need?
This is what gets the data:
function getCurrentGame(summonerID) {
$.ajax({
url: "https://euw.api.pvp.net/observer-mode/rest/consumer/getSpectatorGameInfo/EUW1/" + summonerID + "?api_key=" + APIKEY,
type: 'GET',
dataType: 'json',
data: {
},
What do I need in here:
success: function (resp) {
}
To display the summoner names?
I have this in my HTML to simply build the list from the names:
Current Players (<span id="listPlayers"></span>)
<hr />
<span id="playerNames"></span>
Feel free to amend it in whatever way, I just really can't figure out how to list the player names :(
THANKS!!!
Your whole JSON object is the resp.
Let's say you want to access "gameMode": "ARAM", it will be resp.gameMode.
Let's you want want to access "summonerName": "MLG Elan", it will be resp.participants.summonerName ( because summonerName is inside an array called participants )
Try this
var obj = jQuery.parseJSON( resp );
alert( obj.participants[0].summonerName);
In your json data.participants is an array, you can use Array#map to get all names:
var names = data.participants.map(function(item) {
return item.summonerName;
});
You don't need jquery for that
JSON
var json = yourJSON;
JavaScript
var lenght = json.participants.length;
var summonerName = "";
for (i = 0; i < lenght ; i++){
summonerName += json.participants[i].summonerName.toString() + ", ";
}
document.getElementById("playerNames").innerText = summonerName;
HTML
<span id="playerNames"></span>
The resp parameter is a JavaScript object created by the returned Json. summonerName is an attribute of each participant and participants is an array of objects. So you need to iterate through the participants array and get the name for each participant. Try something like this
success: function (resp) {
var participants = resp.participants,
names = "",
spanElement = document.getElementById("playerNames");
participants.forEach(function(part){
names = names + part.summonerName + " ";
}
spanElement.innerText = names ;
}
I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]
Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.
I use a standard function to retrieve an image within the system, as we have the binary in the database, this works good throughout the whole system.
Currently implementing jqGrid and have some issues to use the current structure as images don't show up and the jquery structure ($obj = $("<div>");) is not useable.
Now I try to implement to get the binary image, however it won't show up, when using a static url it works and image data is being retrieved.
$.extend($.fn.fmatter, {
getBinairy: function (cellValue, options) {
//var object = $();
var width = 50;
var html = "";
getImage(cellValue).success(function (data) {
$.each($.parseJSON(data.d), function (idx, obj) {
p_image = obj.img;
p_type = obj.type;
p_width = obj.width;
p_height = obj.height;
});
var _width = width / p_width;
var _height = _width * p_height;
html = "<img src='data:" + p_type + ";base64," + p_image + "' />";
//object = $("<img/>", {
// src: "data:" + p_type + ";base64," + p_image,
// width: width,
// height: _height
//});
//object.append($img);
});
//var html = "<img src='img/test/20131027_132450.jpg' />";
return html;
},
As far I think the fn is loading the "html" too fast, I can't understand other reason, however have no idea how to avoid this.
Any help?
---UPDATE---
var ip = "";
var station = "";
return $.ajax({
type: "POST",
url: "services/general.asmx/SendBinairy",
data: JSON.stringify({ session: 'ed6d1cc6-82f9-46e8-91bb-eae341a771cf', ip: ip, station: station, id: id }), ///, _filter: JSON.stringify(_json) }),
contentType: "application/json; charset=utf-8",
dataType: "json",
loaderror: function (xhr, status, error) {
},
success: function (data) { }
});
---UPDATE---
"dataset": [
{
"id": 5,
"suffix_type_id": 0,
"sexe_type_id": 1146,
"first_name": "Varvara",
"middle_name": "",
"last_name": "D",
"full_name": "Varvara D",
"company_name": "",
"nickname": "",
"birthday": "1983-12-18",
"age": 31,
"language_type_id": 6,
"relation_type_id": 0,
"job_status_type_id": 404,
"nationality_type_id": 0,
"last_online": "",
"last_online_app_id": 0,
"profile_image": 24,
"profile_rating": 7.000,
"number_contacts": 0,
"number_applications": 0,
"address_id": 0,
"address_1": null,
"address_2": null,
"address_3": null,
"number": 0,
"add": null,
"postal_code": null,
"city": null,
"city_type_id": 0,
"latitude": null,
"longitude": null,
"state": null,
"state_type_id": 0,
"country_type_id": 0,
"address_type_id": 0,
"image": [
{
"file_id": 24,
"binary": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIB
And this is how I add the data to the jqGrid
$("#" + grid_id).jqGrid({
loadonce: true,
type: "POST",
url: "services/general.asmx/HelloWorld",
postData: { q: session },
datastr: colD,
contentType: "application/json; charset=utf-8",
datatype: "jsonstring",
colModel: colM,
rowNum: 10,
rowList: [10, 20, 30],
pager: '#' + grid_id,
sortname: 'id',
viewrecords: true,
sortorder: "desc",
The function getImage is undefined in your code, but I still think that you've chosen wrong way for getBinairy formatter. I suppose that you makes asynchronous Ajax call to the server inside of the formatter. So the function getBinairy returns "" (the initial value of html variable).
I recommend you to change the format of cellValue - the format of data for the column which returned by filling the main grid. For example the data could be JSON encoded object {src:.., width:... , height:... } or {mimeType: ..., charset: ..., base64: ..., width: ... , height: ...} or some other. It's important just that the input data should be full and the formatter will be just produce <img> based on the data without any Ajax calls.