Selecting a subarray in a javascript object using jQuery/jHashtable - javascript

I have an object like this:
var data = {
"info" : [{
"title": "Desemberkonsert",
"description": "MangerFHS 09/10"
}],
"playlist" : [
{
"title": "In This Place",
"description": "Excalibur",
"href": "desemberkonsert_in-this-place",
"url": "flv/desemberkonsert/21_in_this_place.flv",
"thumbnail": "flv/desemberkonsert/21_in_this_place_thumbnail.png",
"time": "5:39"
}]
}
And I am trying to do a search using jHashtables containsValue-function (I am willing to settle for any other search method that works though), like this containsValue(data.playlist, 'Excalibur'). But for some reason, this returns false. How would I select the array that contains the the value Excalibur from the code above?

I could not find a decent method inherently available in JavaScript or the jQuery library, but using a smaller library named jLinq (http://jlinq.hugoware.com/), doing it was a breeze. It allows me to filter with many different methods (I am using the 3.x beta though).
EDIT: The thing I missed was that the lowest arrays behave like objects too. But as Šime Vidas pointed out, I can select a subarray like this: data.playlist[0], and an item within that like this: data.playlist[0].description.

Related

Angular JS ng-options to access object inside object not working

I am trying to create couple select buttons that will be dynamic, and for the first one it worked fine using ng-options.
<select ng-options="muscles.name for muscles in bigdata.muscles track by muscles.id" ng-model="selected"></select>
Now as for the second one, it simple didnt work, or didnt print.
<select ng-options="exercises.name for exercises in bigdata.exercises" ng-model="selected"></select>
and the third one, printed the full array, instead of separating it.
<select ng-options="reps for reps in bigdata.muscles.reps" ng-model="selected"></select>
My Json file looks like this:
{
"name": "Gym App",
"muscles":[
{
"id":1,
"name": "chest",
"reps": [4,6,7,8,9,10,11,12],
"weight": [2,4,6,8,10,12,16,18,20,22,24,26,28,30],
"image": "img/muscles/chest.jpg",
"exercises": [
{
"name": "ALTERNATING FLOOR PRESS",
"rating": 6.1
}, (and goes on with exercises)...
Do objects inside objects need to be treated different?
Thanks
There are some mistakes. muscles is array, not object.
2) replace from bigdata.exercises to bigdata.muscles[0].exercises
3) replace from bigdata.muscles.reps to bigdata.muscles[0].reps
Then, it will work

How to parse JSON with number as a key

I have the following json, I don't have any control over this output unfortunately.
{
"questions": {
"9733": {
"text": "Star Trek or Star Wars?",
"answers": {
"41003": "Star Trek",
"41004": "Star Wars",
"41005": "Neither is superior in my opinion; both great in their own ways",
"41006": "Not a fan",
"41007": "I don't have an opinion on this"
}
},
"25272": {
"text": "Which of these summer movies are you looking forward to the most?",
"answers": {
"99545": "World War Z",
"99546": "Monsters University ",
"99547": "White House Down",
"99548": "Man of Steel",
"99549": "Lone Ranger",
"99550": "The Wolverine"
}
},
"27547": {
"text": "Should the U.S. attack Syria?",
"answers": {
"107453": "Yes",
"107454": "No"
}
}
}
}
I am using json.parse to parse this. To get the text of the first question I would normally do something like this.
var jsonData = JSON.parse(data);//Where data = the json above
console.log(jsonData.questions.9733.text);//Obviously this fails
However javascript doesn't like that number in there obviously. How would you recommend accessing the text of the first question? I would prefer the json to be setup better with in an array of questions instead. Unfortunately I don't have any control over the output of this JSON.
I'm also not going to be aware of the what the keys are as they come across, but thats a whole other issue. I'm willing entertain any suggestions on how to parse this thing as I've never had to parse such a strange JSON output.
You need to use bracket notation:
console.log(jsonData.questions["9733"].text);
But because the value inside the brackets will be automatically converted a string, this would also work:
console.log(jsonData.questions[9733].text);
Note however, that using non-strings is as property names generally bad form and could lead to some subtle problems, e.g. if the property name was "001", then [001] would not work.
Why don't you try?
jsonData["questions"]["9733"]
How to access a numeric property?
I believe you can access the data via same syntax as in an array:
console.log(jsonData.questions[9733].text);
If you have to use numbers as keys... you can access them like this:
var text = jsonData.questions["9733"].text;
Edit: You can also access it with the number 9733. It doesn't have to be a string. Only needs to be a string if the key is non-numeric.
Try using Ason, If you are using Java 8. Gradle dependency compile 'org.arivu:ason:1.0.3'.
Java code as follows
Ason ason = new Ason();
Object json = ason.fromJson("<<JSON String!>>");
System.out.println(Ason.getJson(json, "questions.9733.text", null)):

parsing JSON object with Jquery problem

Hi I am trying to parse the following bit of json with Jquery so far I can get everything out of the results that I want apart from one crucial piece of information the performance tags.
Each json result is wrapped in an event tag and then within this there is info like time and date etc formatted in the following way
"location": {
"lng": -0.1187418,
"city": "London, UK",
"lat": 51.4681089
},
"start": {
"time": "19:30:00",
"datetime":"2010-02-16T19:30:00+0000",
"date": "2010-02-16"
},
I have managed to loop through this and parse it to html. However there is one set of tags for 'performance' that are formatted differently.
"performance": [{
{
"artist": {
"uri": "http://www.songkick.com/artists/288696-vampire-weekend",
"displayName": "Vampire Weekend",
"id": 288696,
"identifier": [{"mbid": "af37c51c-0790-4a29-b995-456f98a6b8c9"}]
}
"displayName": "Vampire Weekend",
"billingIndex": 1,
"id": 5380281,
"billing": "headline"
}
}],
now in my for loop i am running the following code which displays the performance information in the console.
var events = data.resultsPage.results.event;
for (var i = 0, l = events.length; i < l; i++) {
console.log(events[i].performance); }
However when i try to go into the structure like i have been with the other elements I get returned undefined i.e
console.log(events[i].performance.displayName);
Do I have to do this in a different way because of the use of the [ ] brackets in the performance tag in the Json?
Thanks in advance
Assuming that what you posted is not exactly what your JSON looks like (because what's posted has a syntax error), the "performance" attribute is an array of objects. To get at the "displayName", therefore, you'd need to know which element of the "performance" array you wanted. You'd then access it by index.
console.log(events[i].performance[j].displayName);
(assuming you looped through the "performance" array with the variable "j".)
Try to validate your returned JSON object here, I guess there is some issue with the JSON output..

How to retrieve data from json output

I have a json output that looks like this.
{
"38467": {
"name": "Tony Parker",
"book": [
{
"title": {
"name": "MediaWorks"
},
},
],
}
"59678": {
"name": "Ray Thomas",
}
}
Actually json output is a lot bigger list. But I want to only save author's name and their publisher. I want save multiple individual records for a single model.
I am using jquery to assign input elements their values.
$('#Author' + i + 'Title').val(response...);
But it is not working.
I appreciate any help.
Thanks.
JSON is just javascript data - a javascript object. Assign the "decoded" JSON data to a variable (say var dat), then you can access members the normal object/array away: dat[38467]['name'] is Tony Parker and so on.
comment update:
once you've decoded/stored the data, you can use a regular javascript foreach loop to go over it:
for (var bookID in booklist) {
var author = booklist[bookID]['name'];
var title = booklist[bookID]['book'][0]['title']['name'];
// ...do stuff here...
}
There's nothing magical about JSON, it's just javascript data packed up for easy/clean transmission. Of course, if you're using a framework such as jQuery or MooTools, you'd be better off using their own .each() operators, otherwise you'll get various bits of useless fluff from the for() loop.
edit: fixed code sample as per marimuthu's comment (good catch, thanks).

One-liner javascript to collect values from object graph?

Given the following object graph:
{
"children": [{
"child": {
"pets": [{
"pet": {
"name": "fido"
}
},
{
"pet": {
"name": "fluffy"
}
}
]
}
},
{
"child": {
"pets": [{
"pet": {
"name": "spike"
}
}]
}
}
]
}
What would be a nice one-liner (or two) to collect the names of my grandchildren's pets? The result should be ["fido", "fluffy", "spike"]
I don't want to write custom methods for this... I'm looking for something like the way jQuery works in selecting dom nodes, where you can just give it a CSS-like path and it collects them up for you.
I would expect the expression path to look something like "children child pets pet name"
LINQ to JavaScript (JSLINQ) is an implementation of LINQ to Objects implemented in JavaScript. It is built using a set of extension methods built on top of the JavaScript Array object. If you are using an Array, you can use LINQ to JavaScript.
LINQ to JavaScript is an open source project and you can download it from here: http://jslinq.codeplex.com/
Hope this helps...
s
If you don't want to use a library, this is the most concise way I could think of writing it.
var Ar=[];
p.children.map(function(a){a.child.pets.map(function(a){Ar.push(a.pet.name)})});
I settled on the JSONPath library, which is like XPath for JSON. LINQ seemed a little heavyweight for my needs, resulting in a more verbose syntax, though it does look more powerful. Perhaps if my needs change I'll upgrade.

Categories

Resources