Retrieving JSON data using the value of a variable - javascript

Hello. I'm currently working on a small project and have the following issue that I can't seem to solve alone. I have attempted to search for a solution, with no luck. Admittedly, it doesn't help that I'm fairly new at JavaScript/jQuery, so I'm unsure of the "correct" search terms!
I have a JSON file that contains the following code:
var draft = {
"title": "Title",
"subtitle": "Subtitle",
"image": "/image.jpeg",
}
I'm then retrieving the JSON data with the following line:
draft["title"];
Based upon what the application is required to achieve - is there a way to access the JSON data using the value of a variable in place of "draft"? I have an AJAX function that is pulling the file name and extension of the JSON file, and then the following line of code that is refining the file name down to one word by removing the slashes, numbers, hyphens, and file extension:
var fileNameRefined = fileName.replace("/", "").replace(/\d+|-/g, "").replace(".json", "");
As a result, the "fileNameRefined" variable will contain the value "draft". This outputs to the console as expected. That said, it won't work with the JSON. I was hoping that the following lines of code would work in the exact same way:
draft["title"];
fileNameRefined["title"]; // var fileNameRefined = draft
Unfortunately, the resulting data is returned as "undefined". I'm assuming the application is treating the name of the variable as a string as opposed to passing the variable's value? I'm not sure.
Does anybody have a solution to this? Any help would be greatly appreciated.
Thanks, all.

Could be done, SHOULDN'T be done.
Use JSON (This is JS object you presented) and its API. Here is example for jQuery, there are similar examples for other libs/frameworks.
I would always go with fw or lib here for a clear Ajax API over writing it yourself in vanilla.
Here is get JSON example in fiddle (not written by me):
json get fiddle
function getSuccessOutput() {
$.ajax({
url:'/echo/js/?js=hello%20world!',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
},
});
return false;
}
As for JSON api you will be interested in parsing the response using JSON.parse()
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Related

Reading json file

In my ASP.NET backend I am creating json file from a query, I want to use this json file and take some data from it.
I wrote this code:
$(document).ready(function ()
{
$.getJSON("/Content/smartParkTotalJson.json", function (json)
{
});
}
And now I want to see the json , take some data from it (there are many landmarks inside this json file and I want to take the ID element, latitude and longitude).
How can I get access to the things I'm interested in?
In order to parse your json data, use JSON.parse(). Pretty-printing is implemented through JSON.stringify(); the third argument defines the pretty-print spacing.
$.getJSON("/Content/smartParkTotalJson.json", function(data)
{
var obj = JSON.parse(data);
var obj_str = JSON.stringify(obj, null, 2);
console.log(obj_str);
// ...
});
For reading/traversing json objects in javascript, take a look at this simple tutorial. It can represent a good starting point for understanding the basic principles, and unless you provide an example of your json data, also your only choice to perform your data extraction.

Django/JS: json.dumps and parse.json

I'm no programmer, so I can't go to source code of Django or Jquery and figure out how and why these function don't return what I want from them, because I simply wouldn't understand the source code.
I do one little project for myself and here's my confusion about json part:
here's my django/python function:
def searchPatients(request):
patients = Patients.objects.filter(KeyName__icontains=request.POST.get('KeyName'))
response = []
for patient in patients:
tmpvar = {}
tmpvar = { 'Name1':patient.Name1, 'Name2':patient.Name2 }
response.append(tmpvar)
return HttpResponse(json.dumps(response), content_type="application/json")
I checked in shell, json.dumps(response) gave me this:
'[{"Name2": "TestName2", "Name1": "TestName1"}, {"Name2": "TempName2", "Name1": "TempName1"}]'
Looks ok form me. And then I don't understand part starts. This is my JS/JQuery function:
input_newRecord_Search.keyup(function() {
$.post('/edit/ajax_search_patients', { KeyName: $(this).val() }, function(data) {
var patients = jQuery.parseJSON(data);
for (var patient in patients) {
$('#searchResults ul').append('<li>'+patients[patient].Name1+'</li><li>+'patients[patient].Name2+'</li>');
};
}, "json");
});
I get an error: "SyntaxError: JSON.parse: unexpected character".
I checked what data jquery gets from server: console.log(data):
[{Name2: "TestName2", Name1: "TestName1"}, {Name2: "TempName2", Name1: "TempName1"}]
So, as far as I know JSON syntax looks like - {"key":"value"} and I'm missing quotes on key field. And I don't understand why I'm missing them. I can put them manually through regex, for instance, but I don't think it's the right way. And using regex I can parse my entire data without need of jQuery.parseJSON(), but again I want to use jQuery function - after all it was made exactly for this purpose.
Can anyone help me with this one?
The trick is that when you tell jQuery.post that the server is returning JSON it parses it for you.
// This line can be safely removed;
// jQuery is doing it for you behind the scenes
var patients = jQuery.parseJSON(data);
When you use parseJSON on the already parsed data you wind up trying to parse the string representation of a JavaScript object. Simply use the already parsed data and everything should work correctly.
jQuery is automatically converting the json to js objects for you. You don't need to call parse yourself.

get the geolocation from IP , with "ipinfodb"

i know good javascript but totally novice in json and need to do the following:
get the geolocation from IP , with "ipinfodb"
like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with more options like saving the results in cookies
i want the least necessary code to retrieve those informations
for saving them in cookies and more i want to care for it my self after.. (i don't like to put code i dont understand)
the best would be a simple function that returns this information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
thank you all for responding i was trying to filter out the solution, and it works but i'm not yet well satisfied of the result..
i gonna reformulate my question here:
is there i can retrive the geo location from ip with simplest way (javascript) that means without json or jquery..
ajax would be perfect but it doesnt work inter domain (different domains)
thanks again
OK;;174.88.230.88;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
The example you posted isn't valid JSON (you can check if something is valid JSON somewhere like here). That said, looking at the ipinfodb website they appear to have a way to get JSON output using their API (see here).
Once you have valid JSON, you can use JSON.parse. See here for some examples on using it.
So the general idea is
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON reponse)
//(js code using JSON.parse to parse the received JSON reponse)
//(js code to get whatever you want as the result)
return result;
}
As a side note, if you use jQuery you can also use jQuery.parseJSON to parse JSON (see here) which will be more reliable if you anticipate clients using older browsers that might not support JSON.parse.
IP location XML API requires some query strings like &format=json&callback=? additional to ip address in order to get json.
Then you get json like this:
{
"statusCode": "OK",
"statusMessage": "",
"ipAddress": "175.108.204.0",
"countryCode": "JP",
"countryName": "JAPAN",
"regionName": "TOKYO",
"cityName": "TOKYO",
"zipCode": "214-002",
"latitude": "35.6149",
"longitude": "139.581",
"timeZone": "+09:00"
}
Here is a sample code (thanks to #iveoak for good template):
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON response)
var url = 'http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=' + ip + '&format=json&callback=?';
var response = $.getJSON(url); // using jQuery
//(js code using JSON.parse to parse the received JSON response)
response.then(function (location) {
var info = '<ul>';
for (var key in location) {
info += '<li>' + key + ': ' + location[key] + '</li>';
}
info += '</ul>';
});
//(js code to get whatever you want as the result)
return result;
}
If you do not use jQuery, see How can I open a JSON file in JavaScript without jQuery?.
Sample (using jQuery): http://jsfiddle.net/tokkonoPapa/tevB4/
I post another answer.
This is a pure javascript solution using jsonp. Basically, it's a same concept using <script src="http://api.ipinfodb.com/..."></script>.
So you can accsess from anywhere, and do not need to handle json directly. You can simply get the javascript object.
Here is my demo: http://jsfiddle.net/tokkonoPapa/vCTpK/
UPDATE:
I/F is slightly different what you want. It uses a callback function.
getLocFromIP(ip, function(result) {
// use result
});
and the demo returns:
OK;;175.108.204.0;JP;JAPAN;TOKYO;TOKYO;214-002;35.6149;139.581;+09:00
I hope this basic solution satisfies you.

Json object in jquery can't be read?

I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.

Accessing JSON values with a variable

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.
My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:
{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}
I then have a function which is essentially this:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}
}
But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.
Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.
The data access itself works for me:
var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA
Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.
Update: is this your real code? You have at least one syntax error:
function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
alert(data[attrib].label);
}); // <- Please note missing ");"
}
In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).
try to list all properties from data, to have sure the data is being returned:
for (var p in data){
if (data.hasOwnProperty(p){
alert(data[p]);
}
}
It's not your solution but with this you can know how your data is coming.

Categories

Resources