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...
Related
I'm new with Angular, Js etc, and have a problem with understanding how should work with nested data. For example:
I have four json files:
categories
subcategories
posts
comments
It's better to have 4 different files like above, or one like this:
{
"id_category":"1",
"name":"business",
"subcategories":{
"id":"1",
"name":"ecommerse",
"posts": {
"id": 1,
"title": "New post"
"comments": {
"id": 1,
"text": "text text text"
}
}
}
Of course it's only an example, but for that example I need to find comment by Id = 1 to get information about which post this comment is related to, which subcategory and category.
Now I have four different files, and services to get data from json files. I can get a specific comment by ID:
getComment(Id: number) {
return this.comments.find(
(comment) =>
comment.id === Id
);
}
ok, fine. But If I want to get information about post, subcategory, and main category for this comment? What should I do?
It depends on what the specific needs of your application are.
With this structure:
{
"id_category":"1",
"name":"business",
"subcategories":{
"id":"1",
"name":"ecommerse",
"posts": {
"id": 1,
"title": "New post"
"comments": {
"id": 1,
"text": "text text text"
}
}
}
You could iterate over Categories and display a list, then allow a user to select a single category, and assign that to var currentCategory.
You could then iterate over currentCategory.subcategories to allow the user to select a subcategory and assign that to var currentSubCategory. You would keep drilling down then into currentSubCategory.posts, allow the user to select a post, assign that to var currentPost and then iterate over that to display currentPost.comments.
If you're fetching from a database in order to allow the user to drill down into the data for display only, then something like this would work.
If you're maintaining data in JSON files, then I would look at something like JSON Server https://github.com/typicode/json-server
If you're building something more substantial and you have a database backend, make use of the database and don't try to recreate that functionality in your JSON, use JSON as a transport for the data, but don't try to replicate entire tables or complex data structures in your front end code, just fetch what you need as you need it, as that will make for a much more stable and scalable application, and will also make it easier for you do fetch and update data in small manageable chunks.
For mocking a data backend using JSON, consider json-server
https://www.npmjs.com/package/json-server
Goodday fellow programmer,
I'm having trouble adding an object to my JSON file. I'm using jQuery.
My javascript file:
$('#addchallenge').click(function()
{
//hardcoded challenge
var addchallenge =
{
"achievementname": "I am an achievement who want to be added to the list",
"points": "50",
"comment": "guess who has been a nasty achievement to add"
}
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function ()
{
//very suspicious line here:
this["achievementlist"].push(addchallenge);
});
});
});
My external JSON file:
{
"allachievements":[
{
"name": "list of all achievements",
"achievementlist": [
{
"achievementname": "first achievement",
"points": "30",
"comment": "the first achievement to achieve"
},
{
"achievementname": "second achievement",
"points": "-90",
"comment": "is worth a negative amout of points"
},
{
"achievementname": "aaand the 3th achievement",
"points": "30",
"comment": "do you already have achievement 1 and 2?"
}]
}]
}
How could the addchallenge data be added into my JSON file?
Do I need to parse my JSON data, add my challenge to add, then stringify it back?
Thanks in advance :)
You cant directly manipulate the JSON file - Writing, deleting etc.
However, you could write some backend code thats capable of this.
If you simply want to temporally add an achievement, you can parse in your JSON file into a variable and then manipulate it.
You can't modify the JSON file only with client side code. You need some server side code.
I would recommend you to use post().
EDIT:
I actually found this: How to : edit an external json file in javascript
So, current post may be considered a duplicate...
Are you trying to write into a file using jquery?
if so please check the following url:
Read/write to file using jQuery
Your problem is this, the context. Inside of the callback you are passing to $.each iterator, this is not what you think it is.
jQuery.each( array, callback )
callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.
I would change your code like this:
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function (key, value)
{
value["achievementlist"] = value["achievementlist"] || [];
value["achievementlist"].push(addchallenge);
});
});
I have quite a few questions since I'm relatively new at javascript. I started writing this application that lets the user get stock information from the yahoo finance web service and display it on the website. Sounds easy right? I thought so too but I'm having a hard time manipulating the data I'm getting back. Maybe someone can help me get this working. I feel like I'm really close at this point.
The user enters their stock of choice in the stockTextBox such as AAPL or GOOG. Then I set a script attribute with concatenation. Now the confirm() line is VERY odd. If I don't have that confirm in there the alert in the function myCallBack doesn't seem to execute. I can't explain this at all. Maybe I don't now something I should.
Now if I debug I can tell for a back that stock information is coming back from the website. First here is the code and then the JSON data. I would sincerely appreciate it if anyone could help me get this thing to work. I've been fiddling with it for a couple of hours now. THANK YOU! In other words, my question is how do I go about display data that I got from a web service onto my web page?
<form id="stockInput">
Stock Name: <input type="text" id="stockTextBox">
<input type="submit" id="submitButton" value="Submit">
</form>
</b>
<label id="stockLabel"></label>
<script>
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
//tried to put to an element and then read the element value down below through concatenation in the src...
//document.getElementById("stockLabel").innerHTML = textValue;
var script = document.createElement('script');
script.setAttribute('src',"http://finance.yahoo.com/webservice/v1/symbols/"+textValue+"/quote?format=json&callback=myCallBack");
document.body.appendChild(script);
confirm(); //ODD POINT...
}
function myCallBack(data)
{
alert("HEY" + data);
//What I thought I would do. This doesn't output the right info.
//for(key in data)
//{
//alert(data[key]);
//}
}
</script>
</body>
</html>
Now here is the JSON that I can see in the debugger via Firefox:
myCallBack({
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [{
"resource": {
"classname": "Quote",
"fields": {
"name": "Google Inc.",
"price": "1030.579956",
"symbol": "GOOG",
"ts": "1383249600",
"type": "equity",
"utctime": "2013-10-31T20:00:00+0000",
"volume": "1640035"
}
}
}
]
}
});
You are only seeing [object] because it's displaying the data type. You need to get object attributes to obtain the data. The JSON data is very accessible from javascript seeing as how JSON stands for JavaScript Object Notation.
It's very simple once you get started, as the data is basically comprised of objects with attributes and lists of objects. the variable data is your root object, and you can access everything below it easily.
I'll provide a few examples of how you would access certain things in the data:
the attribute "name":
alert(data.list.resources[0].resource.fields.name);
the attribute "classname":
alert(data.list.resources[0].resource.classname);
It's just a text representation of Javascript objects. "resources" is a list of objects, "list" is an object, "fields" is an object, and "price" is a key/value pair to store data.
Read more here: http://www.json.org/
http://www.w3schools.com/json/
If I misunderstood the question let me know, I took a shot at what I thought you meant.
Treat the JSON object like a regular Javascript object. For instance, if you wanted to display the company name and price:
function myCallBack(data)
{
alert("Name: " + data.list.resources[0].resource.fields.name);
alert("Price: " + data.list.resources[0].resource.fields.price);
}
To display the whole thing in raw form for debugging purposes, you can convert it back into a JSON-serialized string:
function myCallBack(data)
{
alert(JSON.stringify(data));
}
More about JSON: https://developer.mozilla.org/en-US/docs/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
I'm trying to display an order summary on the final screen of a checkout process (buit in Rails 3). Nothing is submitted prior to this, so I'm using jQuery's serializeArray() to get all the names and values from the form fields, which works great. I collect a variety of nested attributes, so the returned array is rather busy, with names like order[donations_attributes][0][amount_in_dollars].
Is there a straightforward way, in Javascript (or using jQuery) to convert those names and values to a JSON string (which would make it way easier to work with to produce my summary output). For example, something like:
{
"order": {
"donations_attributes": [
{
"amount_in_dollars": 50.95,
"category": "Some Fund"
},
{
"amount_in_dollars": 90.92,
"category": "Some Other Fund"
}
],
"billing_address_attributes": {
"first_name": "Bob",
"last_name": "Smith",
"address1": "123 Whatever Street",
"and so on": "etc"
}
}
}
Keep in mind that I haven't submitted anything yet (nor can I), so I can't do it in Ruby. Is there a sort of obvious, straightforward way to do this, or will I need to parse out and build the string by hand?
You can pass that data as-is to the data parameter in JQuery.ajax(...), and it will end up in parama in the controller method and view for the action you call, .e.g params[:order][:donations_attributes][0][:category] == "Some Fund".
If you want to load a new url into the browser, you can use JQuery.serialize() on the data and append it to your url (with a `"?" in between) to create the URL with the appropriate query string.