How to access an array in a JSON object? - javascript

I have the following JSON object:
[
{
"comments": [
{
"created_at": "2011-02-09T14:42:42-08:00",
"thumb": "xxxxxxx",
"level": 1,
"id": 214,
"user_id": 41,
"parent_id": 213,
"content": "<p>xxxxxx</p>",
"full_name": "xx K"
},
{
"created_at": "2011-02-09T14:41:23-08:00",
"thumb": "xxxxxxxxxxxxx",
"level": 0,
"id": 213,
"user_id": 19,
"parent_id": null,
"content": "<p>this is another test</p>",
"full_name": "asd asd asd asd asd"
}
],
"eee1": "asdadsdas",
"eee2": "bbbbb"
}
]
This is coming from a $.ajax request, in success I have....
success: function (dataJS) {
console.log(dataJS);
console.log(dataJS[eee1]);
console.log(dataJS.comments);
}
Problem is I can't get access to the items in the JSON object, even though dataJS does show correctly in the console. Ideas?

That's because your base object is an array as well.
console.log(dataJS[0].comments[0]);
I suspect that would work

the JSON you have coming back is actually an array itself, so...
dataJS[0].comments[0].created_at
will be 2011-02-09T14:42:42-08:00, etc...
Both dataJS and comments are arrays, and need indexes to access the appropriate elements.

The object being returned is itself an array, so to get to the first comment (as an example), this is how you would access it:
dataJS[0].comments[0]

console.log(dataJS);
console.log(dataJS[0].eee1);
console.log(dataJS[0].comments[0]);

Do something like this:-
var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}];
var created_at = dataJS[0].comments[0].created_at;

Yes, as others have stated, the JSON is actually an Array (of a single Object). So you will need to reference an index.
Interestingly enough (to me), your result string does validate successfully as JSON. I assumed until now, that to be valid JSON, it had to be an Object (ie, {}).

JSON must be interpreted with eval function (after the obvious sanitization, see security considerations of eval). Are you sure your framework does that for you?

Related

How can I extract data from a JSON file using javascript?

I have this simple variable which I am trying to extract data from. I've parsed it successfully to a json object and tried to print a value based on it a key. But all it says is "undefined". This example I provided is actually a snippet of the json I am trying to manipulate. The full file is actually a json object where one of the elements contains an array of many json objects (these are the ones I ultimately have to access). I have watched countless tutorials and have followed them exactly, but none seem to have this issue.
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
JSON.parse(x);
console.log(x.status);
Can anybody suggest something I may be doing wrong? Thank you!
JSON.parse Return value
The Object, Array, string, number, boolean, or null value
corresponding to the given JSON text. - MDN
You have to assign the parsed result to some variable/constant from where you can use later that parsed value and then use that variable to extract data as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
const parsedData = JSON.parse(x);
console.log(parsedData.status);
or you can directly get value one time after parsed as:
const x = `{
"status": "ok",
"userTier": "developer",
"total": 2314500,
"startIndex": 1,
"pageSize": 10,
"currentPage": 1,
"pages": 231450,
"orderBy": "newest"
}`;
console.log(JSON.parse(x).status);

Json to javascript dictionary

I have JSON data in the following structure, and I'm trying to parse it in order to work with the data using javascript.
JSON Data
{
"FirstItem": {
"id": 1,
"type": "foo",
"colours": ["blue", "black", "green"],
"reviews": {
"positive": ["The best", "unbelievable", "Awesome"],
"negative": ["Sh*t", "Awful", "Dire", "Terrible", "Appalling"],
"neutral": ["OK", "Meh"]
}
},
"SecondItem": {
"id": 2,
"type": "bar",
"colours": ["red", "white", "yellow"],
"reviews": {
"positive": ["Great", "Amazing", "Fantastic", "Perfect", "Uplifting"],
"negative": ["Terrible", "Shocking", "abysmal"],
"neutral": ["OK", "Standard", "Vanilla"]
}
}
}
I am trying to parse this using JSON.parse(), however this returns the following error:
JSON.parse: unexpected character at line 1 column 2 of the JSON data
I have previously worked with this same JSON structure using C#, and had to deserialise this into a dictionary - information can be found on this post
Question
How can I parse this JSON into a javascript object, which will allow me to loop and evaluate each item?
JSON is Javascript Object with double quoted key like what you have in sample. So you don't need to parse it again, see this for explanation. You can access data from it using its key or if in case you want to get reviews from SecondItem, you can access it with :
SecondItem.reviews
or
SecondItem['reviews']
Apparently you are trying to parse an already parsed object
x = {A:1}; // A javascript object
JSON.parse(x); // Error
this happens because JSON.parse will convert the object to a string first, getting "[object Object]" and then will try to parse this string.

Converting JSON from API to collection of "course" objects

I have an end goal of making an application that allows users to put in parameters for their class schedule (i.e "I need Class A, Class B, and Class C, I'd like to take either Class D, G, E, I only want to take 4 classes, and I don't want class before 10am) and then I'd like to present to the user all of their possible schedules (using something like events in Full Calendar http://arshaw.com/fullcalendar/)
I don't know much about working with APIs or JSON (new to JavaScript also) so I'm just a bit overwhelmed with the possibilities on how to do this.
I've searched extensively and found $.getJSON mentioned a lot, so I have something like this:
$.getJSON(
"http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=ACCT",
function(result)
{
}
);
which I believe returns the JSON as a string, yes? Is there a good way to split this into objects or maybe arrays?
Part of the JSON is shown here for brevity:
[
{
"id": 52239,
"title": "Accounting for Decision Making",
"term": "2014 Spring",
"school": "KGSM",
"instructor": {
"name": "Ronald A Dye",
"bio": null,
"address": null,
"phone": null,
"office_hours": null
},
"subject": "ACCT",
"catalog_num": "430-0",
"section": "71",
"room": "Wieboldt Hall 207",
"meeting_days": "Tu",
"start_time": "18:00:00",
"end_time": "21:00:00",
"start_date": "2014-03-31",
"end_date": "2014-06-07",
"seats": 65,
"overview": null,
"topic": null,
"attributes": null,
"requirements": null,
"component": "LEC",
"class_num": 37561,
"course_id": 3,
"coursedesc_set": [],
"coursecomponent_set": []
},
...
...
]
I have tried:
obj = JSON.parse(result);
and suggestions on the web say to follow with something like:
alert(obj.id);
However, this doesn't work, because is seems like the JSON pulled from the API is nested in a way (ie it's all the courses offered in that subject, and each is a JSON). So it doesn't know which "id" value to return. If you look at the link to the JSON you may get a better idea of what I mean. If anyone has any guidance on where to start here it'd be much appreciated. I've just been reading about json and still haven't gotten anywhere.
If I could figure out how to parse the json into each of it's objects, then I could call "all classes with 'time' > 10am for example.
The returned object is an array. You'll need to iterate over each element in the array.
Updated with a working demo:
$.getJSON("http://vazzak2.ci.northwestern.edu/courses/?term=4540&subject=ACCT", function(result) {
var earlyCourses = [];
$(result).each(function (index, item) {
$('#search_results').text((index+1) + " total courses");
if (item.start_time > '10:00:00') {
console.log(item);
$('#morning_results_list').append('<li>' + item.title + '</li>');
}
});
});
With the following boilerplate container:
<h2 id="search_results"></h2>
<div id="morning_results_container">
<h5>Morning Courses</h5>
<ul id="morning_results_list">
</ul>
</div>
Some notes about this example:
The time check here is horribly naive and is reverting to an alphabetical comparison rather than an actual date/time check.
Inserting multiple li in this fashion is bad for UI performance, all updates to the DOM should be batched to a single update. The example of per iteration insertion will work as long as the number of results is small (less than several hundred).
JSFIDDLE EXAMPLE: http://jsfiddle.net/h2a3t/

json get object without knowing it's name

I have some json being returned from a jquery ajax function.
Here is an example of said json:
var b =
{
"SelectByUserResult": [{ "DateAdded": "/Date(1357300130930+0000)/", "Deleted": false, "FileExtension": "jpg", "Filename": "e5d1ee90-f3c0-4dd7-9996-d1725a1fc031.jpg", "Height": 768, "Id": 955, "IsBpMember": true, "OriginalFilename": "Tulips.jpg", "SessionId": "277d31bf-84e1-4678-ad66-e7b332936219", "Title": "New image", "TotalRecords": 16, "UserId": "ded98560-61d0-42f2-944e-30280d54e94b", "Width": 1024}]
}
I have other ajax functions which return similar json in a similar structure, the only difference is the object 'SelectByUserResult' might be changed to 'SelectByIdResult' or 'SelectByNameResult'.
So in my ajax function (in the success function) I would do this to access the json b.SelectByUserResult
I want to be able to access that object but without specifying the name (as it's not always known). How would I go about doing that? Thanks
My funny variant (maybe not the best). It will return the first property of the object, I guess this is what you need.
function getFirstProp(obj) {
for (var i in obj) return obj[i];
}
Usage:
console.log(getFirstProp(b));

Extract value between HTML-tags using JavaScript

How can I extract the value between the tags (49% in message) using Javascript?
I will first parse the JSON with JSON.parse.
{
"id": "189180337778229046",
"from": {
"name": "My FB page",
"category": "Automobiles and parts",
"id": "189180337778229046"
},
"subject": "A good deal",
"message": "<p><strong>49%</strong></p><p>This is a good deal for you.</p>",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yY/r/d1gBp2bDGEuh.gif",
"created_time": "2011-11-02T10:49:56+0000",
"updated_time": "2011-11-02T10:49:56+0000"
}
A simple RegExp will do. Assume obj to hold the value of the parsed JSON string:
var percent = obj.message.match(/<strong>(.*?)<\/strong>/i)[1]; //Returns 49%
Easiest will be to use jQuery which looks like you're already using: (as JSON.parse is part of it)
var myValue = $(data.message).find("strong").eq(0).text();
You can do :
var pattern = /([0-9]+%)/gi;
var result = obj.message.match(pattern);
This will only match integer numbers though..

Categories