{
"Search": [{
"Title": "Batman Begins",
"Year": "2005",
"imdbID": "tt0372784",
"Type": "movie",
"Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"
}, {
"Title": "Batman",
"Year": "1989",
"imdbID": "tt0096895",
"Type": "movie",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"
}],
"totalResults": "291",
"Response": "True"
}
Above is my json response. I want to get title values by using jQuery.
I tried below code... I'm sending request each time when user insert character in text box (on keyup):
url = "https://www.omdbapi.com/?s=" + value;
$.getJSON(url, {
get_param: 'value'
}, function(data) {
$.each(data, function(index, element) {
//console.log(data);
});
for (var prop in data) {
var item = data[prop];
for (var d in item) {
var title = item[d];
console.log(title);
}
}
});
You can use Jquery.each() function to iterate over both arrays and object.
It takes to arguments either array or object as the first argument and a callback function.
since the response is in form of an object you need to run another Jquery.each() on the array holding the objects if you want to implement some logic before that, or just run Jquery.each() on the array it's self:
Here is a sample code that prints the titles on the console:
$.getJSON(url, { get_param: 'value' }, function(data) {
$.each(data.Search, function(index, value) {
console.log(value.Title);
});
});
And here is a JSFiddle
$.each(data.Search, function(obj){
alert(obj.Title);
});
Related
I'm a real noob when it comes to JSON. Any help on the following would be fantastic.
console.log(obj.id); in the code below returns nothing in the console - I need to understand why? I expect it two log two things in the console based on the JSON data.
JS:
var matchTeamAStatsJSON
$.ajax({
type: 'GET',
url: 'http://www.website.com/apipathblahblahblah',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
matchTeamAStatsJSON = data;
console.log(matchTeamAStatsJSON);
for(var i = 0; i < matchTeamAStatsJSON.length; i++) {
var obj = matchTeamAStatsJSON[i];
console.log(obj.id);
}
}
})
JSON:
{
"records": [
{
"id": "recGWUWqwjUNLpekA",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-22T18:16:56.000Z"
},
{
"id": "recx5pMFpxnRwR4La",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-19T11:35:11.000Z"
}
]
}
You could use Array.prototype.forEach() and do:
const data = {"records": [{"id": "recGWUWqwjUNLpekA","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-22T18:16:56.000Z"},{"id": "recx5pMFpxnRwR4La","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-19T11:35:11.000Z"}]};
data.records.forEach(obj => console.log(obj.id));
If the JSON example you posted below is the response from the GET request, data is equal to "records" which doesn't have an and "id" property. However, each instance of the array it contains does.
You need to get inside that array first and then get the "id" property of each element: console.log(obj.records[i].id) should get you want.
Hope this helps!
I'm trying to get the nested station names using jQuery and display the names in a 'div'. I'm able to display the contents of 'jObject' however, I'm unable to get to the specific station name.
This is what i have tried so far.
$.ajax({
url: "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=appid&app_key=key&lat=" + lat + "&lon=" + lng + "&page=1&rpp=5",
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
//console.log(data);
var jObject = data.stations;
// $('#stationName').append(JSON.stringify(jObject));
$.each(jObject.name, function(index, element) {
$('#stationName').append(JSON.stringify(jObject.name));
});
}
});
JSON structure
{
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
}
You should use $each on jObject and not on jObject.name. And you need to specify index while getting name as stations is an array of objects or just use element.name
var data={
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
};
var jObject = data.stations;
$.each(jObject, function(index, element) {
console.log(jObject[index].name);
console.log(element.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There are a few things wrong in your code:
$.each() will iterate on an array, since you already define data.stations as jObject, you need to iterate in that array.
$.each function takes to parameters index and element, the first one is the position of the element in the array, and the second has the element itself.
So the code will be:
var jObject = data.stations;
$.each(jObject, function(index, element) {
$('#stationName').append(element.name);
});
Check the JSFIDDLE
I'm trying to extract the text from this JSON return:
{
"threaded_extended": {},
"messages": [
{
"body": {
"parsed": "the network. Take a moment to welcome Jason.",
"plain": " network. Take a moment to welcome Jason.",
"rich": "Jason."
},
"thread_id": 56,
"client_type": "Wb",
"client_url": "https://www.yammer.com/",
"system_message": true,
"direct_message": false,
"chat_client_sequence": null,
"language": "en",
"notified_user_ids": [],
"system_message_properties": {
"subtype": "created_membership"
},
"privacy": "public",
"attachments": [],
"liked_by": {
"count": 0,
"names": []
},
"content_excerpt": " Jason.",
"group_created_id": null
}
]
}
my function looks like this, but it keeps saying undefined - sorry if this is a dumb question, my logic is that the object is value, then messages is an attribute, and then plain should be an attribute of that. Am I doing something stupid? Appreciate any help
function getData(returnData){
$.each(returnData, function(key, value){
if(value != undefined){
$('#test').append(value.messages.plain);
}
});
}
$('#test').append(value.messages[0].plain);
messages is an array so you need to provide an index.
Edit : I thought returnData was an array, if it's not the case you're looping on the wrong object. Loop through returnData.messages. and get value.body.plain
Iterate through returnData.messages the array in your object. Then you can access each message item in the array, whereas the plain value is on body.plain for each value
function getData(returnData){
$.each(returnData.messages, function(key, value){
if(value != undefined){
$('#test').append(value.body.plain);
}
});
}
I need help pushing the values from a filtered json, I need this generate a nested ul list, I can not modify the json format at this point, I you check the console.log you will see the values to create the list, at this point I can't figure how to complete the 'for loop' to render the html markup needed, any help will be appreciated, this is the jsfiddle http://jsfiddle.net/43jh9hzz/, and if you check the console log you will see the values.
This is the Js:
var json='';
var property_set = new Set();
function iterate(obj, stack) {
json="<ul>";
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
}
else {
// console.log(property);
property_set.add(property);
json+="<li>";
if(typeof obj[property] !== "number") {
json+="<li>"+obj[property]+"</li>";
console.log(obj[property]);
}
}
} json += "</li>";
}
}
var listEl = document.getElementById('output');
iterate(jsonObj)
And this is the json format:
var jsonObj =
{
"level_1": [
{
"level_1_name": "CiscoSingaporeEBC",
"level_2": [
{
"level_2_name": "Khoo Tech Puat",
"level_2_id": 2222,
"level_3": [
{
"name": "Boon Leong Ong",
"id": 6919
},
{
"name": "Kiat Ho",
"id": 6917
},
{
"name": "Overall Experience",
"id": 6918
}
]
}
]
},
{
"level_1_name": "CiscoLondonEBC",
"level_2": [
{
"level_2_name": "Bernard Mathews Ltd.",
"level_2_id": 2367,
"level_3": [
{
"name": "Barry Pascolutti",
"id": 7193
},
{
"name": "Kathrine Eilersten",
"id": 7194
},
{
"name": "Martin Rowley",
"id": 7189
}
]
},
{
"level_2_name": "FNHW Day 1",
"level_2_id": 5678,
"level_3": [
{
"name": "Jurgen Gosch",
"id": 7834
},
{
"name": "Overall Experience",
"id": 7835
}
]
},
{
"level_2_name": "Groupe Steria Day 1",
"level_2_id": 2789,
"level_3": [
{
"name": "Adam Philpott",
"id": 7919
},
{
"name": "Pranav Kumar",
"id": 7921
},
{
"name": "Steve Simlo",
"id": 7928
}
]
}
]
}
]
};
enter code here
I'm not sure if I am interpretting your request correctly, but I think this is what you want: http://jsfiddle.net/mooreinteractive/43jh9hzz/1/
Basically, you are calling the iterate function to run, but then that's it. The function actually needs to also return the value it generates.
I've added to the end of the function, after the for loop completes:
return json;
Do now the function returns the value it generated, but there are some other issues too. When you recursively call the iterate function again inside the iterate function, you actually want to add what it returns to the current json string housing all of your returned value.
So on that line I changed it from:
iterate(obj[property], stack + '.' + property);
to
json += iterate(obj[property], stack + '.' + property);
Now that other value will come back as well inside the main list you were creating in the first run of the function. Ok so that's pretty close, but one more small thing. I think when you added additional surrounding LI, you actually wanted to do an UL. I changed those to ULs and now I think the result is like a UL/LI list representing the text parts of the JSON object.
Again, that may not be exactly what you were after, but I think the main take away is using the function to return the value, not just generate it, then do nothing with it.
I have to create a column chart in my project using Highchart. I am using $.ajax to populate this data. My current JSON data is like this :
[{
"city": "Tokyo",
"totalA": "10",
"totalB": "15"
},
{
"city": "Seoul",
"totalA": "20",
"totalB": "27"
},
{
"city": "New York",
"totalA": "29",
"totalB": "50"
}]
How to resulting JSON string look like this:
[{
"name": "city",
"data": ["Tokyo", "Seoul", "New York"]
}, {
"name": "totalA",
"data": [10, 20, 29]
}, {
"name": "totalB",
"data": [15, 27, 50]
}]
Thank you.
Assuming all the elements look the same (they all have the same fields): Live Example
// src is the source array
// Get the fields from the first element
var fields = Object.keys(src[0]);
// Map each key to...
var result = fields.map(function(field) {
// Grab data from the original source array
var data = src.reduce(function(result, el) {
// And create an array of data
return result.concat(el[field]);
}, []);
// Format it like you want
return {name: field, data: data};
});
console.log(result);
If they aren't, the code is slightly more complicated: Live Example
// Work out the fields by iterating all of the elements
// and adding the keys that weren't found yet to an array
var fields = src.reduce(function (fields, current) {
return fields.concat(Object.keys(current).filter(function (key) {
return fields.indexOf(key) === -1;
}));
}, []);
var result = fields.map(function (field) {
// Need another step here, filter out the elements
// which don't have the field we care about
var data = src.filter(function (el) {
return !!el[field];
})
// Then continue like in the example above.
.reduce(function (result, el) {
return result.concat(el[field]);
}, []);
return {
name: field,
data: data
};
});
console.log(result);