I am new to Json and JavaScript. Currently I have a url which returns a JSON response. But the problem is that, It is not in correct format. Please see my response below
var pd={ player:
{ id: 363609002,
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
dateCheck: 1487204427149,
dateUpdate: 1474581052618,
dateCreate: 1384980182606,
dateStreak: 1474581052618,
lastDay: '20160715',
country: '',
countryName: null,
rank:
{ nr: 121,
imgLarge: 'bf4/ranks/r121.png',
img: 'r121',
name: 'Major General II',
needed: 16110000,
next:
{ nr: 122,
imgLarge: 'bf4/ranks/r122.png',
img: 'r122',
name: 'Major General III',
needed: 16750000,
curr: 16720600,
relNeeded: 640000,
relCurr: 610600,
relProg: 95.40625 } },
score: 16724643,
timePlayed: 1476950,
uId: '2832665149467333131',
uName: 'm4jes',
uGava: '721951facb53ed5632e196932fb6c72e',
udCreate: 1319759388000,
privacy: 'friends',
blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
editable: false,
viewable: true,
adminable: false,
linked: false },}
from the above response I have to get the output as :
{
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
score: 16724643,
timePlayed: 1476950
}
By which method I can get the required out in Javascript
First of all the URL is not returning a JSON response but a JS object literal. The difference is explained here.
You have to get the string from the url. You can use the jQuery method get():
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
//Insert the rest of the code here
});
</script>
Then, jqxhr.responseText is the string which correspond to the object we want. With eval, we transform the string into an object:
pd = eval(jqxhr.responseText);
So here we have an object literal with all the pairs name/value. You can access the values you want by using the dot notation. If you want to get the name of the game for example, you can write this:
pd.player.game
So this leads to :
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
Then, you have to transform this JS object literal into a JSON by using the JSON.stringify() method:
console.log(JSON.stringify(myNewObject, null, '\t'));
It returns what you want:
{
"game": "bf4",
"plat": "pc",
"name": "m4jes",
"tag": "BPt",
"score": 16724643,
"timePlayed": 1476950
}
So here is the full code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
pd = eval(jqxhr.responseText);
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>
Related
[I have a JSON array that contains some values,How can i retrieve the IsDefault value from this array.][1]
I have tried userDefaultPagePreference[0].Isdefault but i am getting isDefault Undefined
Object
userDefaultPagePreference : Array(1)
0 :
date: "2018-04-17T15:48:42.66"
defaultUrl: null
error: []
id:3
isDefault:true
pageName: "ChangeMyAccountSettings"
userId: "e8dfee00-6224-4a29-851e-7c10343eba9a"
Define your variable like this
let userDefaultPagePreference: any[1] = [{
0: null,
date: "2018-04-17T15:48:42.66",
defaultUrl: null,
error: [],
id: 3,
isDefault: true,
pageName: "ChangeMyAccountSettings",
userId: "e8dfee00-6224-4a29-851e-7c10343eba9a"
}];
And Test userDefaultPagePreference[0].isDefault like this
console.log(userDefaultPagePreference[0].isDefault)
Observation :
You are trying to access Isdefault but it should be isDefault.
DEMO
var obj = {
"userDefaultPagePreference": [{
"date": "2018-04-17T15:48:42.66",
"defaultUrl": null,
"error": [],
"id": 3,
"isDefault": true,
"pageName": "ChangeMyAccountSettings",
"userId": "e8dfee00-6224-4a29-851e-7c10343eba9a"
}]
};
console.log(obj.userDefaultPagePreference[0].isDefault);
Accessing an element in a JSON array in typescript here will be like this:
userDefaultPagePreference[0]['Isdefault']
I'm trying to get the data with json to generate a footable table with pagination but it's not working.
my code actualy look like this.
sorry my bad english.
my index.json is returning it
{
Cartas: [
{
id: 3,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "teste",
contrato: "",
grupo: "430",
cota: "3332",
credito_atual: 154371.02,
prazo_original: "",
prazo_atual: "126",
valor_parcela: "0",
pc_pago: 1,
pc_fc: 0,
valor_pago: 154371.02,
saldo_devedor: null,
taxa: 0,
data_compra: "2003-03-28T00:00:00+00:00",
created: "2017-06-22T17:39:23-03:00",
data_contemplacao: "2016-12-20T00:00:00+00:00",
data_entrega: null
},
{
id: 4,
user_id: 1,
status: "2",
banco_cartas: null,
nome: "CAS REP comerciais",
contrato: "",
grupo: "240",
cota: "320",
my jquery to load the json in footable
jQuery(function($){
$('#custom-ui-example').footable({
"columns": [
{ name: "nome",
title: "Nome"},
{ name: "credito_atual",
title: "Crédito Atual"},
{ name: "status",
title: "Status"}
],
"rows": $.get("index.json")
})};
my html
<table class="table" id="custom-ui-example" data-paging="true"></table>
Index.json should return array of objects, in your case it is returning object.
The format of the json should be
[{'id': '3'},{'id': '4'}]
Pagination seems to work fine.
Find the working fiddle here: https://jsfiddle.net/qwwjs7j3/
first of all, you should check if your json is valid. you can do that here for example: https://jsonformatter.curiousconcept.com/
then you can should make the get-call using:
$.get({
url: 'index.json'
}).done(function(data) {
data = JSON.parse(data);
});
the return data is hold in the data object of the callback function.
The POSTED DATA is EMPTY but why its like this. Pls check!!!
function AData(mid,murl,mdata)
{
$.post( murl, mdata)
.done(function( data ) {
$("#res"+mid).html(data);
});
}
AData('1','http://api.techsoul.in/movies/techsoul-update-movies.php?token=777&fun=addmovie','{ detail:"PHA%2BTW92aWUgRGV0YWlscyBPZiA6IEFycml2YWwgPC9wPjxiciAvPgo8cD4gQSBNb3ZpZSBEaXJlY3RvciBOYW1lIDogRGVuaXMgVmlsbGVuZXV2ZTwvcD48YnIgLz4KPHA%2BIENhc3RpbmcgSW4gTW92aWUgOiBBbXkgQWRhbXMsIEplcmVteSBSZW5uZXIsIEZvcmVzdCBXaGl0YWtlcjwvcD48YnI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D4gQ291bnRyeSBGcm9tIDogVVNBPC9wPjxiciAvPgo8cD4gTGFuZ3VhZ2UgVXNlZCA6IEVuZ2xpc2g8L3A%2BPGJyIC8%2BCjxwPiBHZW5yZXMgc2VlbXMgOiBEcmFtYSwgTXlzdGVyeSwgU2NpLUZpIDwvcD4%3D",category:"aG9sbHl3b29kLW1vdmllcy0yMDE2",poster:"aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE2LzExL0Fycml2YWwtTW92aWUtUG9zdGVyLmpwZw%3D%3D",rate:"MA%3D%3D",year:"MjAxNg%3D%3D",quality:"TkE%3D",name:"QXJyaXZhbA%3D%3D",genre:"RHJhbWEsIE15c3RlcnksIFNjaS1GaQ%3D%3D",link:"aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L2Fycml2YWwtMjAxNi1mdWxsLW1vdmllLW9ubGluZS1mcmVlLWhkLw%3D%3D",src:"aHR0cDovLzE2My4xNzIuMjE0LjEwNS95a2dpcGltZWs2MmJpcm1wbmh3Z3J6bHJlMjZkajI1d29veTZ0Y2Y2MzdhM2ZnamRiY3duanc0c3V3aGEvdi5tcDQ%3D",playersrc:"aHR0cDovL3B1dGxvYWQudHYvZW1iZWQtdDBpNDZodXplMG5lLmh0bWw%3D",status:"MQ%3D%3D" }');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='res1'></p>
Because you passing your parameter mdataas a string, not as an object. Remove the single quotes before and after, format your json correctly as an array and it works:
var details = [
{
detail: "PHA%2BTW92aWUgRGV0YWlscyBPZiA6IEFycml2YWwgPC9wPjxiciAvPgo8cD4gQSBNb3ZpZSBEaXJlY3RvciBOYW1lIDogRGVuaXMgVmlsbGVuZXV2ZTwvcD48YnIgLz4KPHA%2BIENhc3RpbmcgSW4gTW92aWUgOiBBbXkgQWRhbXMsIEplcmVteSBSZW5uZXIsIEZvcmVzdCBXaGl0YWtlcjwvcD48YnIgLz4KPHA%2BIFJlbGVhc2VkIFllYXIgOiAyMDE2PC9wPjxiciAvPgo8cD4gQ291bnRyeSBGcm9tIDogVVNBPC9wPjxiciAvPgo8cD4gTGFuZ3VhZ2UgVXNlZCA6IEVuZ2xpc2g8L3A%2BPGJyIC8%2BCjxwPiBHZW5yZXMgc2VlbXMgOiBEcmFtYSwgTXlzdGVyeSwgU2NpLUZpIDwvcD4%3D",
category: "aG9sbHl3b29kLW1vdmllcy0yMDE2",
poster: "aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE2LzExL0Fycml2YWwtTW92aWUtUG9zdGVyLmpwZw%3D%3D",
rate: "MA%3D%3D",
year: "MjAxNg%3D%3D",
quality: "TkE%3D",
name: "QXJyaXZhbA%3D%3D",
genre: "RHJhbWEsIE15c3RlcnksIFNjaS1GaQ%3D%3D",
link: "aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L2Fycml2YWwtMjAxNi1mdWxsLW1vdmllLW9ubGluZS1mcmVlLWhkLw%3D%3D",
src: "aHR0cDovLzE2My4xNzIuMjE0LjEwNS95a2dpcGltZWs2MmJpcm1wbmh3Z3J6bHJlMjZkajI1d29veTZ0Y2Y2MzdhM2ZnamRiY3duanc0c3V3aGEvdi5tcDQ%3D",
playersrc: "aHR0cDovL3B1dGxvYWQudHYvZW1iZWQtdDBpNDZodXplMG5lLmh0bWw%3D",
status: "MQ%3D%3D"
},
{
detail: "PHA%2BTW92aWUgRGV0YWlscyBPZiA6IEFycml2YWwgPC9wPjxiciAvPgo8cD4gQSBNb3ZpZSBEaXJlY3RvciBOYW1lIDogRGVuaXMgVmlsbGVuZXV2ZTwvcD48YnIgLz4KPHA%2BIENhc3RpbmcgSW4gTW92aWUgOiBBbXkgQWRhbXMsIEplcmVteSBSZW5uZXIsIEZvcmVzdCBXaGl0YWtlcjwvcD48YnIgLz4KPHA%2BIFJlbGVhc2VkIFllYXIgOiAyMDE2PC9wPjxiciAvPgo8cD4gQ291bnRyeSBGcm9tIDogVVNBPC9wPjxiciAvPgo8cD4gTGFuZ3VhZ2UgVXNlZCA6IEVuZ2xpc2g8L3A%2BPGJyIC8%2BCjxwPiBHZW5yZXMgc2VlbXMgOiBEcmFtYSwgTXlzdGVyeSwgU2NpLUZpIDwvcD4%3D",
category: "aG9sbHl3b29kLW1vdmllcy0yMDE2",
poster: "aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L3dwLWNvbnRlbnQvdXBsb2Fkcy8yMDE2LzExL0Fycml2YWwtTW92aWUtUG9zdGVyLmpwZw%3D%3D",
rate: "MA%3D%3D",
year: "MjAxNg%3D%3D",
quality: "TkE%3D",
name: "QXJyaXZhbA%3D%3D",
genre: "RHJhbWEsIE15c3RlcnksIFNjaS1GaQ%3D%3D",
link: "aHR0cDovL29ubGluZW1vdmlld2F0Y2hzLnR2L2Fycml2YWwtMjAxNi1mdWxsLW1vdmllLW9ubGluZS1mcmVlLWhkLw%3D%3D",
src: "aHR0cDovLzE2My4xNzIuMjE0LjEwNS95a2dpcGltZWs2MmJpcm1wbmh3Z3J6bHJlMjZkajI1d29veTZ0Y2Y2MzdhM2ZnamRiY3duanc0c3V3aGEvdi5tcDQ%3D",
playersrc: "aHR0cDovL3B1dGxvYWQudHYvZW1iZWQtdDBpNDZodXplMG5lLmh0bWw%3D",
status: "MQ%3D%3D"
}
];
AData(
'1',
'http://api.techsoul.in/movies/techsoul-update-movies.php?token=777&fun=addmovie',
details
);
Edit: In first version on this post, I did not see, that your json was not valid. Look at my answer now and it should work without any errors. Also, please inform youself about the JSON standard and fit it to your needs.
I am new to JSON to AS3 Objects and am having issues trying to create an AS3 object that I can reference. Here is the JSON:
{
demo: {
Male: {
21-30: 2,
31-40: 0,
41-50: 0,
51-60: 0,
61-70: 0,
71-80: 0,
81+: 0
},
Female: {
21-30: 7,
31-40: 0,
41-50: 0,
51-60: 0,
61-70: 0,
71-80: 0,
81+: 0
}
},
days: 0
}
Here is the parsing code:
var JSONRequest: URLRequest = new URLRequest();
JSONRequest.method = URLRequestMethod.POST;
JSONRequest.url = "https://www.urlhere.com;
var loader: URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleResponse);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.load(JSONRequest);
function handleResponse(event:Event):void{
var returnData:String = loader.data;
var parsedData:Object = JSON.parse(returnData);
}
I have tried and successfully looped through the object with for loops, but I don't want to have to do that, I want to be able to access the data as an object or array by accessing the properties in dot syntax. Object[0].property etc...
The really tricky part is that I don't know how large or how deep the data is nested. The one I added here is simple.
Here is more like what I will be getting:
{
products: {
Home & Garden: {
Kitchen: {
202: {
brand: "OXO",
description: "12 piece locktop container set",
descriptionLong: "Prepping, cooking and cleaning",
listPrice: "36.32",
sku: "925776",
upc: "719812032528"
},
238: {
brand: "Excalibur",
description: "Excalibur 2400 4-Tray Dehydrator",
descriptionLong: "Dehydration is the healthiest",
listPrice: "168.54",
sku: "947741",
upc: "029743240009"
},
352: {
brand: "Nostalgia",
description: "OldFashioned Kettle Corn Maker",
descriptionLong: "With the Nostalgia Electrics ",
listPrice: "35.49",
sku: "925843",
upc: "082677300218"
},
370: {
brand: "Joseph Joseph",
description: "Nest Plus Measuring (Set of 5 Cups - Multi Coloured)",
descriptionLong: "Nestâ„¢ Cups are a range of 5",
listPrice: "2.46",
sku: "926733",
upc: "5028420400342"
},
605: {
brand: "Nostalgia",
description: "Margarator-Frozen Drink Maker",
descriptionLong: "Mix up great-tasting margaritas",
listPrice: "140.68",
sku: "925851",
upc: "082677135889"
}
},
Housewares: {
206: {
brand: "Dyson",
description: "Dyson DC44 Animal",
descriptionLong: "DC44 Animal has a detachable",
listPrice: "406.51",
sku: "922846",
upc: "879957006362"
}
}
}
I will also add that I can request the formatting of the JSON I am receiving, so if there is a better way to format the data coming from the server, I am open to that.
Any help would be great.
I want to be able to access the data as an object or array by accessing the properties in dot syntax.
Use JSON.stringify and a replace callback before the parse call to rename the keys so you can access them via dot notation:
function newkey()
{
return "key" + Number(Math.random() * 1000).toFixed() + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify(parsedData);
/*
Replace numeric keys with a random number without replacing the delimiter
Replace spaces with underscores
*/
var bar = foo.replace(/\d+("?:)/g, newkey).replace(/\s/g,"_")
//Parse resulting string
var baz = JSON.parse(bar);
References
JSON - AS3 API Reference
How to parse below JSON code in JavaScript where iterators are not identical?
var js= {
'7413_7765': {
availableColorIds: [ '100', '200' ],
listPrice: '$69.00',
marketingMessage: '',
prdId: '7413_7765',
prdName: 'DV by Dolce Vita Archer Sandal',
rating: 0,
salePrice: '$59.99',
styleId: '7765'
},
'0417_2898': {
availableColorIds: [ '249', '203' ],
listPrice: '$24.95',
marketingMessage: '',
prdId: '0417_2898',
prdName: 'AEO Embossed Flip-Flop',
rating: 4.5,
salePrice: '$19.99',
styleId: '2898'
},
prod6169041: {
availableColorIds: [ '001', '013', '800' ],
listPrice: '$89.95',
marketingMessage: '',
prdId: 'prod6169041',
prdName: 'Birkenstock Gizeh Sandal',
rating: 5,
salePrice: '$79.99',
styleId: '7730'
}
}
How can I parse this JSON in JavaScript? I want the values of prdName, listprice, salePrice in JavaScript?
var products = js; // more semantic
for (productId in products){
var product = products[productId];
console.log (product.prdName , product.listprice, product.salePrice);
}
js is an Object, the for (key in instance) iteration moves through the first level object's attributes, in this case 7413_7765, 0417_2898 and prod6169041, this keys are stored in the var productId, so products[productId] will return the value of this attributes.
Note that the "" in object keynames are not necesary.
You have already assigned the JSON to an object js.
You're trying to loop through JavaScript object, as Edorka mentioned iterate it.