Reading json file - javascript

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.

Related

Retrieving JSON data using the value of a variable

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"}');

Need to grab the JSON here from an external file

This code does what I need but I want to store the JSON values it uses in a separate file using standard JSON format so the same data can be used elsewhere with getJSON requests.
(I need to run this to match up data returned from a getJSON request with additional values. I use the id to do the match on returned items. This is how I build the complete HTML items I need.)
CODE SAMPLE
$(function() {
var json = {
"nwsltrs":[
{
"id":"53c57dede4b07621dafde5d1",
"nwsltrNames":"Hello",
"author":"Joe"
} // these entries will grow to a hundred or more.
]
};
var titleID = "53c57dede4b07621dafde5d1"; // in actual code getting this value from a separate getJSON call
$.each(json.nwsltrs, function(i, v) {
if (v.id === titleID ){
nwsltrName = v.nwsltrNames;
author = v.author;
console.log(nwsltrName + ":" + author);
return;
}
});
});
Want the external JSON file to look like this with and use .json extension:
{
"nwsltrs":[
{
"id":"53c57dede4b07621dafde5d1",
"nwsltrNames":"Hello",
"author":"Joe",
},
{
"id":"54b57dede4b07621dafde5d2",
"nwsltrNames":"Bye",
"author":"Mary",
} // these entries will grow to a hundred or more.
]
I'm sure there are better ways to approach this and am open to hearing them—as long as I can use an external JSON file.
Solved.
Moved getJSON request that was tried earlier before posting.
It needed to run and return the data prior to this .each.
This allows me to replace the local JSON function and use a validated external JSON file here and elsewhere as desired.

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...
I'd like to store dialog in JSON format...
Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:
function getJson() {
var json = {
"people" :
[
{//NPC 1 - rescue dog
etc...
Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`
var json = getJson();
Then use it as such:
Labels[index].text = json.people[index].dialogs.start.texts[0];
Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?
Thanks!
It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt
On the other hand if an API is serving this data it need not have any extension at all.
It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.
So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:
{
"people" :
[
{//NPC 1 - rescue dog
...
}
]
}
If you choose to use jQuery:
var dialog;
$.getJSON('json/dialog.json', function(data) {
dialog = data;
// Asynchronous success callback.
// Now dialog contains the parsed contents of dialog.json.
startGame();
});
Keeps your data separate from your logic.

Json can not be parsed when received dynamically (using socket.io)

I am receiving json-datas which is 100% correct formatted json data.
My problem is,
when I run the following code it works:
var data = {"datas":[{"matts":{"active":"1","status":"off"},"config":null,"adapters":[]}}]};
console.dir(data); // it works.
but when I receive the same data on socket.io like following code, its not working:
_liveSock.on('sm', function(data)
{
console.log(data); // I am receiving the data correctly.
console.dir(data); // But I cant display the data.
});
Both codes are almost the same logic, only the second one is received dynamically.
When I try to use console.dir(data); on second code, it gives this error:
there is no kind object
(btw. I am using Firefox/Firebug)
Is there another method or way to use dynamically received json datas?
Thank you!
You can't use console.dir() until you have parsed the value.
console.dir(JSON.parse(data));
The JSON facility is not available in older browsers. You can find parsers online.

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