extract an URL from a JSON response of wikipedia api - javascript

I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.

Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.

Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.

Related

How do I place a json value using jquery?

I am sending selected fields to an API(3rd party app) from wordpress.
This is how my data array looks like:
var data_array = {
"order": {
"customer": {
"name": "The User"
}
}
}
I want to substitute the value of the "name" key to a javascript variable that contains a jquery selector. For example:
var name = j('.billing_company_name').html(result.meta_data[1].value);
I am thinking that the new code for the data_array will be:
var data_array = {
"order": {
"customer": {
"name": name(variable name jquery selector)
}
}
}
Do you know the correct syntax so I can substitute the value of "name" key with the value of the jquery selector?
The final code will look like the code below:
j.ajax({
type: 'POST',
url: 'http://mywebsite/api/orderdetails',
cache: false,
data: {
"data_array": data_array
},
beforeSend: function() {
},
success: function(result) {
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {
}
});
I need the value of the element to be place inside the value of data_array.order.customer.name
In this case you can use val() to select that property. If you want to do it as you instantiate the object, use this:
var data_array = {
"order": {
"customer": {
"name": name.val()
}
}
}
Or if you want to do it after declaring data_array (which is badly named, as it's an object not an array), then you can use this line:
data_array.order.customer.name = name.val();

Parsing JSONP file with JavaScript

How do I access the Marie-Antoinette.json object in this JSON file? I would like to get the title element of the object but I can't seem to get it to output. Here is my JavaScript code which outputs the object but I cant seem to access the objects elements.
$.ajax(
{
type: 'GET',
url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7',
//contentType: "application/json; charset=utf-8",
dataType: "JSONP",
jsonpCallback: 'callback',
//async: false,
success: function(r)
{
alert("ok");
$.each(r, function(index, value){ // iterating over each object
console.log(index);
if(index == "_attachments")
{
console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object?
}
});
}
});
Here is the file. The elements I would like to access are in the "_attachments" element of the object.
{
"_id": "efadd5913f5cfd254b2861efd4001cb7",
"_rev": "6-417588bbff9aa74726b11440a86a8532",
"_attachments": {
"Marie-Antoinette.json": {
"content_type": "application/json",
"revpos": 2,
"digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==",
"length": 761,
"stub": true
}
}
}
I think what is throwing me off is that it is an object inside the _attachment section.
The Marie-Antoinette.json object is inside your _attachments object, but because it contains a . it can't be accessed using dot-notation. You'll have to use array-like notation, passing the key as a string like so:
success: function (response) {
console.log(response._attachments['Marie-Antoinette.json']);
}
If you have multiple "attachments", you can access them in a loop like this:
success: function (response) {
$.each(response._attachments, function (i, attachment) {
console.log(attachment);
});
}
You could use Object.keys to extract keys from _attachments object and then print it:
var title = Object.keys(r._attachments)[0];
console.log(title);
Or if you have multiple attachments:
var titles = Object.keys(r._attachments);
console.log(titles.join());
Object.keys always returns an array.
in your function:
success: function(r)
{
for (key in json._attachments) {
console.log(key); // gives the names
console.log(json._attachments[key]); // gives the content
}
}
that would give you the stuff in _attachments

How to parse json response in jQuery mobile?

I am new to jquery mobile. I am trying to get contact name from contacts. JSON by sending AJAX request. But I am not getting any alert when I click on submit button.
My jQuery ajax request
$(document).ready(function() {
//after button is clicked we download the data
$("#submit").click(function(){
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function(data) {
var json = $.parseJSON(data);
alert(json.name);
});
});
});
contacts.json
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
.
.
.
.
]
}
How to generate dynamic clickable list for above ajax response?
dataType: "json"
already specifies the returned data to be a json object. so to read the values, you can simply use the object syntax:
success: function(data) {
//cycle trough returned "contacts":
for(var i=0;i<data.contacts.length;i++){
console.log(data.contacts[i].name);
}
}
from the looks of it, your json will be an array of object. Try doing json[0].Name to test it
your json data present inside contacts,so you should take name in this format.
var json = $.parseJSON(data);
alert(json.contacts[0].name);
Firstly our code is badly formated (smart quotes, wrong placement of parentheses). Secondly since your contacts are in an array, you can't access them using json.name, you should try something like this instead:
$(document).ready(function () {
//after button is clicked we download the data
$("#submit").click(function () {
//start ajax request
$.ajax({
url: "myURL/contacts.json",
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
json.contacts.forEach(function(val, ind, arr){
alert(val.name);
});
}
});
});
});
In stead of parsing JSON you can do like followng:
$.ajax({
..
dataType: 'json' // using json, jquery will make parse for you
});
To access a property of your JSON do as shown in below:
data[0].name;
data[0].email;
Why you need data[0] because data is an array, so to its content retrieve you need data[0] (first element), which gives you an object {"name":"myName" ,"address": "myAddress" }.
And to access property of an object rule is:
Object.property
or sometimes
Object["property"] // in some case
So you need
data[0].name and so on to get what you want.
If you not
set dataType: json then you need to parse them using $.parseJSON() and to retrieve data like above.

How can I convert a json object to an array in javascript

Here is a snippet of javascript from my C# web MVC application:
$.ajax({
url: 'myurl'
}).done(function(response) {
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The JSON response form this call looks like this
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": {
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}
}
}"
I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": [{
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}]
}
}"
I tried something like this which didn’t work:
$.ajax({
url: 'myurl'
}).done(function(response) {
var tmp;
if (!respose.renditons.rendition.isArray) {
tmp = respose.renditions.renditon;
respose.renditon = [];
respose.renditon.push(tmp);
}
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.
Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code
Try this:
$.ajax({
url: 'myurl'
}).done(function(response) {
var json = JSON.parse(response);
if(!Array.isArray(json.renditions.rendition)) {
json.renditions.rendition = [json.renditions.rendition];
}
return json;
});
Fiddle demo (kind of...)
You can check if the object is an array using this:
Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'
And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:
if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
response.renditions.rendition = [response.renditions.rendition];
}
Fiddle demo.
add data type JSON to your ajax post. example
$.ajax({type: "POST",
url: URL,
data: PARAMS,
success: function(data){
//json is changed to array because of datatype JSON
alert(data.renditions);
},
beforeSend: function (XMLHttpRequest) {
/* do something or leave empty */
},
complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },
dataType: "json"}
);

How to use a JavaScript to load and parse a static JSON file in the server

I'm just starting to use javascript and json.
I need to read data (getInformation function) from a json file when processing an event in a javascript function. So I need it to be synchronic. I don't know if I am missing something in the code, or if I have to create an Request and handle the callback, or if I need to import additional javascript to use json. Because I don't know how to make it work. It doesn't work because at the end the array is empty. Any help is aprreciated.
The json file:
{"Users": [
{"Name": "Jane",
"Points": 67,
"age": 23},
{
"Name": "Sam",
"Points": 65,
"age": 21}
]}
Option 1 - Function called by another function which is processing an event:
var getInformation = function()
{
var path = "./data/users.json";
var informationArray= [];
console.log("Loading ....");
$.getJSON(path, function(data)
{
$.each(data, function(key, val)
{
informationArray.push(key + '-' + val);
});
});
return informationArray;
}
Option 2 - Function called by another function which is processing an event:
var getInformation = function() {
var path = "./data/users.json";
var informationArray= [];
$.ajax({
url: path,
async: false,
dataType: 'json',
success: function(response) {
$.each(response.items,
function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
return informationArray; }
I have seen the following thread and tried what is there but doens't work for me. I would like to know where is the problem in my code or if require any special configuration.
Thread: Is there a version of $getJSON that doesn't use a call back?
When JavaScript is running in a browser it needs to make an AJAX request to the server to access a JSON file. It is possible to write the AJAX request by hand but that is complex and difficult to make work in all browsers. Instead most people use a library like jQuery. You will need to include jQuery in your web page with something like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
Then in any script tag lower in the html page you should be able to do something like:
$.ajax({
url: "data/users.json",
dataType: "json",
success: function(response) {
$.each(response.Users, function(item) {
informationArray.push(item);
});
informationArray.push("success");
}
});
see http://api.jquery.com/jQuery.ajax/
To load a JSON file (and not require a callback) you'd use:
var url = 'http://yoursite.com/data/users.json';
var j = [];
$.ajax({
type: 'GET',
url: url,
dataType: 'json',
success: function(data) { j = data;},
async: false
});
alert(j.Users[0].Name);

Categories

Resources