please i have this output from my json web service:
{"format":"json",
"success":true,
"errors":[],
"result":
{"**206**":
{"player_name":"stagiaire",
"M":{
"6480":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6481":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6482":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
"6483":{"score":0,"answer":"cdgvbdbgd","category_name":"cdgvbdbgd"},
},
"O":{
..... },
}
}
}
What i want is to extract the value (which is now 206 but it can be another number).
I am asking for your help to achieve this goal.
Any help will be appreciated.
In case the resulting object contains only a single property with this number as its name, i.e.
result = {
206 : {
...
}
// no other properties here
}
then you can use something like:
var num = Object.keys(result).shift(); // "206"
Check the browser compatibility for Object.keys() method at MDN and use shim if needed.
If the object you look for always has a player name as value, try
for (var key in obj.result) if obj.result[key]["player_name") alert(key)
Or use jQuery
$.each(data.result,function(key,val) {
alert(key);
});
Related
How do you reference a JSON object in JavaScript?
I have a JSON response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON by way JSON.Parse(response)
Sample JSON:
{
"HotelListResponse":{
"customerSessionId":"",
"numberOfRoomsRequested":1,
"moreResultsAvailable":true,
"cacheKey":"",
"cacheLocation":"",
"cachedSupplierResponse":{
"#supplierCacheTolerance":"NOT_SUPPORTED",
"#cachedTime":"0",
"#supplierRequestNum":"101",
"#supplierResponseNum":"",
"#supplierResponseTime":"",
"#candidatePreptime":"14",
"#otherOverheadTime":"",
"#tpidUsed":"",
"#matchedCurrency":"true",
"#matchedLocale":"true"
},
"HotelList":{
"#size":"20",
"#activePropertyCount":"101",
"HotelSummary":[
{
"name":"name1"
},
{
"name":"name2"
}
]
}
}
}
How can I, for example reference the customerSessionId? And the second HotelSummary name?
For customerSessionId I have tried jsonObject.customerSessionId which returns undefined. For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name which is undefined too.
Given the JSON string above parsed and assigned to a variable as such:
var response = JSON.Parse(jsonString);
you should be able to access it like this:
var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle
As you can see, you need to reference HotelListResponse,
so if your var result holds your json object, then you can fetch the values by using
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name
Given the following json result, how can I convert the validationErrors key/value property into a nice array object in javascript so i can then do things like
errors[0].Key
or
errors[0].Value, etc...
NOTE: If it's easier to do the conversion with jQuery, then I'm happy to use that. Also, I'm getting the data via jQuery -> $.post...)
update:
Here's the actual json data so someone can answer this with JSFiddle please.
{
"aaaa": 0,
"bbbb": 0,
"cccc": null,
"validationErrors": {
"a1_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "Invalid PropertyType. Please choose any property except Unknown.",
"a2_7127763-1c7ac823-61d5-483f-a9ca-4947e9eb8145": "A State is required. Eg. Victoria or New South Wales.",
"b1_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "Invalid PropertyType. Please choose any property except Unknown.",
"b2_5433417-18b5568a-d18e-45e2-9c63-30796995e2d3": "A State is required. Eg. Victoria or New South Wales.",
"c1_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "Invalid PropertyType. Please choose any property except Unknown.",
"c2_6655305-297c57f9-a460-4101-be7d-70c6b9a565d5": "A State is required. Eg. Victoria or New South Wales."
}
}
I would take all the keys of the object and then map them to an array.
var arrayOfErrors = Object.keys(objectOfErrors).map(function(errorKey) {
return objectOfErrors[errorKey];
});
You can use map to convert the object to an array:
var errors = jQuery.map(data.validationErrors, function (value, key) {
return {
"Key": key,
"Value": value
};
});
JSFiddle showing this approach: http://jsfiddle.net/WgaFb/1/
If you do not wish to use jQuery, here is a pure JavaScript method:
var errors = [];
for(var key in data.validationErrors) {
errors.push({
"Key": key,
"Value": data.validationErrors[key]
});
}
JSFiddle for this second approach: http://jsfiddle.net/4WXEF/1/
I have some JSON which I have in a object but I can seem to return the values a sample of the json is as follows.
{
"rootLayout":"main",
"layoutDescriptions":[
{
"id":"main",
"container" : {
"type":"Tabs",
"content":[
{
"type":"Panel",
"label":"Simple Address",
"layout":"SimpleForm",
"comment":"This form is simple name value pairs",
"content":[
{ "type":"label", "constraint":"newline", "text":"Org Name" },
{ "type":"text", "property":"propOne" },
{ "type":"label", "constraint":"newline", "text":"Address" },
{ "type":"text", "property":"addrLine1" },
{ "type":"text", "property":"addrLine2" },
{ "type":"text", "property":"addrLine3" },
{ "type":"label", "constraint":"newline", "text":"Postcode" },
{ "type":"text", "property":"postcode" }
]
},
I am trying to return the rootLayout using
obj[0].rootLayout.id
This doesn't work also I am wondering how to access the content elements.
I am new to json and I have been thrown in the deep end I think. I cannot find any good reading on the internet can anyone recommend some.
Thanks.
Some explanation because you don't seem to understand JSON
It's not as complicated as one may think. It actually represents javascript objects as if they'd be written by code.
So if you have JSON written as:
{
id : 100,
name: "Yeah baby"
}
This means that your object has two properties: id and name. The first one is numeric and the second one is string.
In your example you can see that your object has two properties: rootLayout and layoutDescriptions. The first one jsonObj.rootLayout is string and will return "main" and the second one is an array:
layoutDescriptions: [ {...}, {...},... ]
Apparently an array of objects because array elements are enclosed in curly braces. This particular array element object that you provided in your example has its own properties just like I've explained for the top level object: id (string), container (another object because it's again enclosed in curlies) etc...
I hope you understand JSON notation a bit more.
So let's go to your question then
You can get to id by accessing it via:
jsonObj.layoutDescriptions[0].id
and further getting to your content objects:
var contentObjects = jsonObj.layoutDescriptions[0].container.content[0].content;
for(var i = 0; i < contentObjects.length, i++)
{
// assign this inner object to a variable for simpler property access
var contObj = contentObjects[i];
// do with this object whatever you need to and access properties as
// contObj.type
// contObj.property
// contObj.text
// contObj.constraint
}
Mind that this will only enumerate first content object's content objects... If this makes sense... Well look at your JSON object and you'll see that you have nested content array of objects.
The object is an object, not an array, and it doesn't have a property called 0.
To get rootLayout:
obj.rootLayout
However, rootLayout is a string, not an object. It doesn't have an id. The first item in the layoutDescriptions array does.
obj.layoutDescriptions[0].id
Are you trying to get one of layoutDescriptions with id equals to obj.rootLayout?
var targetLayout = {};
for(var i = 0; i < obj.layoutDescriptions.length; i++) {
if(obj.layoutDescriptions[i].id == obj.rootLayout) {
targetLayout = obj.layoutDescriptions[i]; break;
}
}
console.log(targetLayout);
I get the following error in IE8:
length is null or not an object
Anyone have any ideas? Feedback greatly appreciated.
function refresh() {
$.getJSON(files+"handler.php?action=view&load=update&time="+lastTimeInterval+"&username="+username+"&topic_id="+topic_id+"&t=" + (new Date()), function(json) {
if(json.length) {
for(i=0; i < json.length; i++) {
$('#list').prepend(prepare(json[i]));
$('#list-' + count).fadeIn(1500);
}
var j = i-1;
lastTimeInterval = json[j].timestamp;
}
});
}
Just check for the object being null or empty:
if (json && json.length) {
// ...
}
C'mon gang this was glaringly obvious :-)
JSON objects (returned by jQuery or otherwise) do not have a length property. You'll need to iterate over the properties, most likely, or know the structure and simply pull out what you want:
$.getJSON( ..., ..., function( json ) {
for( var prop in json ) {
if( !json.hasOwnProperty( prop ) ) { return; }
alert( prop + " : " + json[prop] );
}
} );
Alternatively, grab a library like json2 and you'll be able to stringify the object for output/debugging.
pop the JSON in a span then clip it and paste it here so we can see it:
<span id="JSObject2">empty</span>
with the json2.js from here: (link for it at bottom of the page) http://www.json.org/js.html
myJSON = JSON.stringify(json);
$('#JSObject2').text(myJSON);
Using that, we can help you better, and you can see what you have!
What does your returned JSON look like? If you're returning an object, length might not be explicitly defined, whereas if you're returning an array, it should be defined automatically.
First thing that comes to mind is that length is not a property of whatever json is. What is the json variable supposed to be anyway?
A JSON is an object, you seem to be treating it like an array. Does it really have a length property? Show us the JSON?
You might need to use a for..in instead.
EDIT: Can you make the JSON from the backend structure like so?
({
"foo": []
})
It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
foreach my $var (#vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):
{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
But every time I do this, firebug throws the following error:
"XML filter is applied to non-xml data"
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.dataset_two.data;
Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.
Your example is failing because of some convoluted logic I just caught.
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
Now, the foreach loop goes through the variable data.results to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be name = "datasets_a" item = object. Following me so far? Now you access the returned hash, the object in item, as though it has the child key in name ... "datasets_a". But wait, this is the object!
If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
Why would you want to change an array into another array ?-)
-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)
This works. Just dump it into a script block to test.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
}
alert(d.results.datasets_a.dataset_one.data.sample)
I hope this pasted in correctly. This editor doesn't like my line breaks in code.
d = {
'results':{
'datasets_a':{
'dataset_one':{
'data':{
'sample':'hello'
},
'extra_info':{
//stuff
}
},
'dataset_two':{
///
}
///
},
'datasets_b':{
///
}
}
};
alert(d.results.datasets_a.dataset_one.data.sample)