File Naming Conventions .json or .js? - javascript

So, I'm trying to create some helpful JSON files that other can use to prototype out applications using State JSON data with image names that correspond to actual images I have in the same directory.
Here are my files : https://github.com/tannerjt/state_images.json
My question is this... since JSON is just javascript, should I use .json or .js for files.
One of my files is technically JSON, but I named it states.js, since it is an array of javascript object...
[
{
"name": "Alabama",
"abbreviation": "AL",
"capital": "",
"image": {
"image_name": "alabama.jpg",
"location": "Monte Sano State Park",
"credit": {
"author": "Wes Thomas (BamaWester on Flickr)",
"url": "http://www.flickr.com/photos/bamawester/3493269235/"
}
}
},....
]
Because I called it a .js file, I added
var states = [{...
to the beginning. With it being an Array of json object... JSONlint still validated it.
Any thoughts? I want to make this useful for people to play around with, but not sure how I name the files correctly.

if you included var states = [{... in your raw text and tried to parse the thing as a json object, it would probably fail. Saving it as a .json file and leaving it only with data would be a preferred option.

Related

Error saving JSON file

I have following JSON file:
weather = [
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
I am new to working with JSON files. I want to save this JSON file as weather.json.
But it gives following error:
Expected value at 1:0 pointing to the first line of the file.
You can't have weather = in your JSON file. JSON stands for JavaScript Object Notation so anything other than a JavaScript Object won't work. You also can't have functions in there. Take a look at the JSON official website to see what the format accepts
This should be correct:
[
{
"city": "Munich",
"temp": {
"temp_val": "30 deg",
"temp_unit": "C"
},
"speed": {
"speed_val": 7.31,
"speed_unit": "m/s"
}
}
]
You can then add this line in your javascript once you load the file into a string:
weather = JSON.parse(some_string);
You are manipulating this file as if it was going to be rendered as JavaScript. This should only be plain text, no variable definitions. Just plain key value pairs. If you want to assign variable, set it to a .js file and render it in a browser.
You should look at an example file for JSON and model it. Remember that JSON is just plain text organized in a particular way.

How Do I See the Output of Changes to JSON

Updated to try to be more clear given the comments (Thank you for comments)
I apologize in advance for this question. I may just not have the vocabulary to properly research it. If I have an array of objects called restaurants stored in my project, for example:
restaurants: [
{
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I then run a function to add a unique idea to all the objects in the array. The result of console.log(restaurants) is this:
{
"id": 3472,
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"id": 9987,
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I would now like to have this updated array of objects available to look at in my project, via the text editor, as a variable or restaurants.json file. How do I actually see the new modified json array and how do i save it so that i can work with it the same way i did this one above? I am currently doing this in the browser. I can see the results if i log it to the console but I need to be able to work with the new output. Thanks for taking the time to answer.
You can encode/decode JSON with JSON.stringify() and JSON.parse().
Aside from converting to/from JSON, you work with standard JS objects and arrays:
var array = JSON.parse(json_str);
array[0].address = "5th Avenue";
console.log(JSON.stringify(array));
Well, there's really not enough information in your question but I assume a few things:
You've loaded the json data from somewhere and it has been turned into a javascript object.
You've edited the object somehow and wish to convert it back to json and save the changes.
Assuming the above to be true, you just need to serialize the object back to json and submit it back to your server where you can save it in any manner you deem appropriate.
You can serialize the javascript object with JSON.stringify() (see https://stackoverflow.com/a/912247/4424504)
Add the serialized json to a hidden field on the form and submit it.
On the server when processing the form submission, grab the data from the hidden field and do with it what you wish.
Or get it back to the server any way you wish (ajax call, whatever) the key point is to serialize the object to a json string and save it
Hope that helps...

Json format issue in d3 pack layout

I am very new to d3. I have 3 days old d3 knowledge. I was trying to make one pack layout but I am not able to call translate(of transform) function based on the data in external json file. My json file is not formatted as name, children order (which has been used most of the examples). So, can any one clarify that whether we must have the json file in proper format like in tree structure to get the proper pack or tree layout. My json file format is:
{
"sourcefile":"Script",
"structure":{
"Links":[
[
"step1",
"port1",
"step2",
"port2"
],
[
"step3",
"port3",
"step4",
"port4"
]
],
"device":{
"step1":{
"args":{
"pin":[
"XXXX",
100
]
},
"device_type":"console"
},
"lock":{
"args":{
"username":[
"XXXX",
"test"
],
"address":[
"XXXX",
"10.0.0.1"
]
},
"device_type":"Light"
}
}
}
}
It it's true..I was wondering if anyone can tell me about some online tool to format this json file into the following format..
{
"name": "Names",
"children":
[
{ "name": "John", "size": 100 }
]
}
Your intuition is correct. The pack layout requires input data formatted as a hierachy. It seems unlikely that an online tool to convert general JSON data to this structure would exist, as such a tool would almost have to be custom-built for each particular data set. However, d3 itself has utility functions to help you to create the required structure. I'm referring to the Nest utilities. Looking at your input data, it's not at all obvious how to structure it in a hierarchy, so I can't offer any specific implementations suggestions. In general, though, I'd suggest transforming your data into a simple array of objects and then use the d3.nest utilities to extract the hierarchy from the data.

How to structure and parse JSON

I'm creating a web RPG using HTML5 and JavaScript embedded directly into my website. The game will be a single player game against computer opponents... the design will be top-down 2D, Zelda style. It will be real time, but conversing with computer players will be scripted... they say something, and you're given some response options.
I was thinking of writing the dialog in XML, but I was told I should use JSON as it's easier to parse using JavaScript.
I saw Abstract Chaos' answer in XML...
<?xml version="1.0" encoding="UTF-8"?>
<npcs>
<npc name="Abstract">
<dialogue>
<text>Welcome #{PlayerName} to Stack Exchange, What would you like to know? </text>
<options>
<option action="dialogue5">Tell me about Stack Exchange?</option>
<option action="quest1">Give me quest</option>
<option action="object1">Give me object</option>
</options>
</dialogue>
<dialogue id="5">
<text>Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics</text>
<text>We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise</text>
</dialogue>
</npc>
</npcs>
And was wondering how I could achieve the same sort of layout in JSON...
My questions are:
How can I layout RPG dialog scripts in JSON to be parsed by JavaScript?
Can I have an example of how I could use JavaScript logic to parse JSON given certain conditions (ex: NPC asks question: "Can you help me?", JSON should have options "Yes" and "No", which could be based on if the player actually has that skill set to help).
The JSON dialog text will be stored in a separate "dialog" folder in my project folder... so it will need to be accessed externally
The only thing I've found on how to layout and parse JSON is:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
alert(obj.result);
But it doesn't have the neatness factor that XML seems to have.
Any help would be appreciated...
Thanks!
Trying to load and alert external JSON text file doesn't work:
HTML:
<html>
<head>
<title>Working with JSON</title>
<script src="jquery.js"></script>
<script>
(function() {
var data = "/JSON_TEXT.txt";
var first_q = data.npcs[0].dialogs[0];
alert(first_q.text);
}());
</script>
</head>
<body>
</body>
</html>
JSON plain text file: JSON_TEXT.txt
'npcs': [
{
'name': 'Abstract',
'dialogs': [
{
'text': 'Welcome',
'options': [
'df', 'f'
]
}
]
}
]
How can I layout RPG dialog scripts in JSON ?
The equivalent of the XML you gave us would be (without the comments):
// you might use a top wrapper object with a property "npcs" for this array
[
{
"name": "Abstract",
"dialogues": {
// I recommend on object with dialogues by id instead of an array
"start": {
"texts": [
"Welcome #{PlayerName} to Stack Exchange, What would you like to know?"
],
"options": [
{
"action": "dialogue 5",
"text": "Tell me about Stack Exchange?"
}, {
"action": "quest 1",
"text": "Give me quest"
}, {
"action": "object 1",
"text": "Give me object"
}
]
},
"5": {
"texts": [
"Stack Exchange is a fast-growing network of 87 question and answer sites on diverse topics",
"We build libraries of high-quality questions and answers, focused on the most important topics in each area of expertise"
]
}
}
// further properties of the NPC like objects and quests maybe
},
… // further NPCs
]
How to parse JSON?
See Parse JSON in JavaScript?.
var json = {…};
var data = JSON && JSON.parse(json) || $.parseJSON(json);
Ouch, no! That's no JSON, that's just an object literal in JavaScript. You can use it like
var data = {…};
and data will be your object. You need to parse JSON only when you have it as a string, for example when you've loaded a file via ajax.
JavaScript logic to parse JSON given certain conditions
That's your game logic, with which we can't help you. But you don't need to parse JSON there, you only need to access the data which you have already parsed. See Access / process (nested) objects, arrays or JSON for that.
Some find JSON harder to read than XML. I think it's much cleaner and easier to use, especially if you want to parse it with JS.
That said, I'm not really sure what your question is—you already have the data in XML, so just convert it to JSON. You can use arrays ([]) for lists and objects ({}) for when you need named keys:
{
'npcs': [
{
'name': 'Abstract',
'dialogs': [
{
'text': 'Welcome #{PlayerName} to Stack Exchange, What would you like to know?',
'options': [
//options here
]
},
//next dialog object here
]
},
//next npc object here
]
}
So, like you said, first you'll need to parse the JSON string:
var json; //contains the json string, perhaps retrieved from a URL via AJAX
data = JSON && JSON.parse(json) || $.parseJSON(json);
You could also assign the JSON object to a JS variable in the first place (say, in a .js file somewhere) and you won't need to parse at all. Just be sure not to pollute the global scope.
After parsing, data is a normal JS object. You can access its properties just like any other object. So, to access the first question from the first NPC, do:
var first_question = data.npcs[0].dialogs[0];
Let's alert the question itself:
alert(first_question.text);
You can access its options like this:
first_question.options;
You asked about how to load the JSON data from an external file. The usual approach is to load the file's URL via AJAX. Here is a nice tutorial for making AJAX requests with vanilla JavaScript: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
But there's not much reason to hand-code AJAX requests with vanilla JavaScript. I recommend using a library like jQuery, which has handy AJAX functions such as .ajax and the shorthand function .get. Here's an example using .get:
var data; //will hold the parsed JSON object
var json_url = 'json.txt'; //URL of your JSON (just a plain text file)
$.get(json_url, function(json) {
data = JSON && JSON.parse(json) || $.parseJSON(json);
});
//use data here

Parse JSON from local url with JQuery

I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.
I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.
So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.
This is a sample output of my url:
[
{
"baken": "not implemented...",
"deviceType": "Optimus 2X",
"batteryLevel": "1.0",
"gps": {
"speed": 0,
"Date": "TueNov0100: 34: 49CET2011",
"Accuracy": 35,
"longitude": {removed},
"latitude": {removed},
"Provider": "gps"
},
"deviceId": "4423"
},
{
"baken": "notimplemented...",
"deviceType": "iPhone",
"batteryLevel": "30.0",
"gps": {
"speed": 0,
"Date": "TueNov0116: 18: 51CET2011",
"Accuracy": 65,
"longitude": {removed},
"latitude": {removed},
"Provider": null
},
"deviceId": "4426"
}
]
Hope you can help me..
If you are running a local web-server and the website and the json file are served by it you can simply do:
$.getJSON('path/to/json/file.json', function(data) {
document.write(data);
})
If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.
If you are using Chrome you can try the --allow-file-access-from-files parameter for developing purposes.
Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)
Edit: To parse it you can use jQuery.parseJSON
jQuery.parseJSON('{"foo": "goo"}');
$.get('/some.json', function(data) {
// data[0]["baken"] == "not implemented..."
});
See http://api.jquery.com/jQuery.get/
You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.
For your example if you put the results in a variable called data then you could do things like this:
data[0].deviceType // would be "Optimus 2x"
data[0].gps.speed // would be numeric 0
etc.
The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:
$.ready(function() {
// put your other code for page initialization here
// set up a global object, for namespacing issues, to hold your JSON.
// this allows your to be a good "web" citizen, because you will create
// one object in the global space that will house your objects without
// clobbering other global objects from other scripts, e.g., jQuery
// makes the global objects '$' and 'jQuery'
myObjects = {};
// start JSON retrieval here
$.getJSON('/path/to/json/file.json', function(data) {
// 'data' contains your JSON.
// do things with it here in the context of this function.
// then add it to your global object for later use.
myObjects.myJson = data;
});
});
The API documentation is here

Categories

Resources