How to create a JSON feed - javascript

I have a file called parsing.html that parses through a xml feed and converts the metadata into JSON Object called "data". I'm trying to output this JSON "data" as a JSON feed such as http://www.videws.com/gtv/videosources.php. Is doing
document.write(JSON.stringify(data)) the equivalent of creating a JSON feed in this case?
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
//document.write(categories);
category.videos.push(video);
}
data.categories.push(category);
}
});
document.write(JSON.stringify(data));
}
})

im not sure you fully understand what http://www.videws.com/gtv/videosources.php is doing.
if you look at the source code it appears not to have any javascript at all so its not doing a document.write, it is more likely doing all of the conversion to JSON within PHP server side then streaming out.
a good help site for using PHP with JSON is available here: http://www.tutorialspoint.com/json/json_php_example.htm
i would say that if your more of a JS/HTML guru you may get more out of NODEJS than PHP but that's entirely up to you.

Related

how to display json resful data using javascript or jquery

how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});

How can I append json data if object key is equal to a predefined value?

I have got an ajax GET request that pulls in data through a loop. What I am trying to achieve is to get posts that are relevant but are not in the predefined id value of the current post you are on. So I have this function below:
var _permId = $('#work-area').data('current-id');
var getRelatedPosts = function() {
$.ajax({
url: '/wp-json/posts?type=case-studies&filter[taxonomy]=awards&filter[term]='+_awardsPart+'',
success: function ( query ) {
//List some global variables here to fetch post data
// We use base as our global object to find resources we need
// _permId is the var that tells me the current id of this post
var posts = query;
postFull = [];
for(var i = 0; i < posts.length; i++) {
//terms.push(term);
var postObject = posts[i];
postFull.push(postObject);
for (var key in postObject) {
//console.log(postObject[key]);
if (postObject[key] === _permId) {
console.log('this is the same as this post');
}
}
};
},
cache: false
});
};
What I want to do is not allow any content through if the post object id is the same value as _permId.
Here is an idea of the json that is retrieved with keys and values:
Object {ID: 4434, title: "new brand case", status: "publish", type: "case-studies", author: Object…}
The ID is the value I want to set an argument against.
You haven't to loop on the object if you just want to check the ID :
...
postFull = [];
for(var i = 0; i < posts.length; i++) {
var postObject = posts[i];
postFull.push(postObject);
if(postObject.ID === _permId) {
//they have the same id
}
};
EDIT :
To get the datas you want you can use $.grep :
var newArray = $.grep(posts, function(e, i){return e.ID !== _permiId;});
or in pure JS
var newArray = [];
for(var i = 0; i < posts.length; i++){
var p = posts[i];
if(p.ID !== _permId){
newArray.push(p);
}
}

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

fuzzy search (fuse.js) using XML instead of JSON

Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});

Javascript Function Returns Undefined JSON Object (But It's Not Undefined!)

I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});

Categories

Resources