How would one load a javascript structure (object or array) from a file in Cocos2d-X 3.
My res/test.json:
{
version:"1.0",
data:"this is some data."
}
I'm able to load the file content like so:
var data = fileUtil.getStringFromFile('res/test.json');
cc.log(data);
What is the best way to load the javascript structure from the string? Is there a function in cocos2d-x to do this directly?
The "standard" JSON.parse works:
var fileUtil = cc.FileUtils.getInstance();
var data = fileUtil.getStringFromFile('res/test.json');
var jData = JSON.parse(data);
But note all attribute names must be passed in quotes, otherwise the parser will fail. res/test.json must then look like this:
{
"version":"1.0",
"data":"this is some data."
}
Related
I'm new to Json and node.js
I'm trying load my json file into a jsonobject using node.js.
But I'm unable to do so.
I've created 2 files one is server.js and jsonresponse.json. I need to load the jsonresponse.json in json object created in server.js using javascript or node.js.
This is snippet of server.js
var file = 'jsonresponse.json'
jsonfile.readFile(file, function(err, obj) {
jsonObject = console.dir(obj);
})
suppose my json data is in myDirectry/data.json
//data.json
{
"a":2,
"b":3
}
So my myDirectory/app.js should be.
var x=require('./data');//or require('data');
console.log(x);
In order to read ,only require() is enough though u can read it using fs.But the best way is to require.
While the following code will give you the object in procedural way you should keep in mind the asynchronous behaviour of node.
var jsonfile = require('jsonfile')
var file = 'jsonresponse.json'
var jsonObject = jsonfile.readFileSync(file)
As you are starting with node, you should get familiar with the callback pattern
In the snippet provided by you the file is being loaded in callback and you should be accessible within that scope.
var file = 'jsonresponse.json';
var jsonObject;
jsonfile.readFile(file, function(err, obj) {
//on success obj is the data therefore it holds the reference to contents of the file
if(!err){
jsonObject = obj;
}
else console.log(err);
})
jsonfile.readFile is called withe the filename and a callback function. Once it completes the task of reading file it invokes the callback function with 2 parameters: error and data.
error is null if theres no problem, otherwise it contains the error details.
data contains whatever data the function wanted to return.
If you need to avoid caching (file changes between calls) do this
var fs = require('fs')
var obj = JSON.parse(fs.readFileSync('myfile.json').toString())
I have 6 json files in the same directory as my index.htm. Each json structure has saved game data in it. I want to let the user choose a file and load its associated json data structure. How can I go about retrieving that data?
I tried using
var myjson = new Object();
$.getJSON("myJSON.json", function(json) {
myjson = JSON.stringify(json);
console.log(myjson);
});
This gives me an XMLHttpRequest error (cross-origin request not supported).
Your execution is fine -- though like the comments on your post suggest, you need to change the protocol you're using. Really just load the HTML page using http://127.0.0.1/mypage.html instead of file://home/website/mypage.html and you can likely keep your javascript the same.
Aside from this, you might want to consider the data in your myJSON.json file. I noticed if the JSON data contains function definitions then it will cause $.ajax() or in this case $.getJSON() to throw a parse error.
So this will not work
{
"json" : function () {
alert("HI");
},
"hello" : 432
}
But this will work
{
"json" : "5",
"hello" : 432
}
I have this small code example:
<script type="text/javascript">
var texts = [{key:'key_1', value:'value_1'},
{key:'key_2', value:'value_2'},
{key:'key_3', value:'value_3'}];
</script>
I use a json array directly in my xhtml page by using the script tag. The json array "texts" is used by an another java script function in my xhtml page, but that is not important at the moment.
How can a extract this json array into an external file? Which library it must be used?
EDIT:
I use a java maven project and that should be include my external json file!
I tried this code but it doesn´t work:
<script type="text/javascript">
var placeholderTexts = himjQuery(document).getJSON('placeholder.json');
</script>
You can use each loop in jQuery
Just try this
$.each(texts, function(key, value) { }
please try the below.
var arraysel;
var json = { };
for(var i = 0, l = arraysel.length; i < l; i++) {
json[arraysel= [i].id] = arraysel= [i].value;
}
After reading many times your question, I think what you want is this:
Create a .js file, for example data.js, with your data... which is not a JSON-serialized object, but a real literal. Use pure JSON notation if you want.
var DATA = {"a":1, "b":2};
Import that "script" wherever you want to use your data.
<script type="text/javascript" src="./data.js></script>
Use this data from any place in your JS code, for instance:
console.log(DATA.a);
Please get JSON data from AJAX and evaluate response and store in variable
<script>
var placeholderTexts = new Object();
$(function(){
$.get('placeholder.json', function(data){
try{
placeholderTexts = jQuery.parseJSON(data);
console.log(placeholderTexts)
}catch(e){
alert(e.toString());
}
});
});
</script>
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.
This seems like a simple problem but I have a coder's mental block:
The concept:
I type a URL, i.e - www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345
and instead of getting back a webpage or something I want to get back a json object so that I can parse on a different page.
The catch:
I can certainly accomplish this by calling a MVC controller with those parameters and returning a json object. However, Let's say I need to create this json object inside a js file that takes those parameters' values from the URL and I get my json back as the result.
The questions
Can I pass parameters to a js file and return a json object? Or
Can I call a js file from a controller and pass it these parameters to and retrieve a json object?
Do I even need to call a controller via a URL, or can I just call a js file giving it parameters from a URL and then returning the json?
What is the proper/best way of handling this scenario, with MVC, js, jquery...anything??
Thanks a lot guys!
You have a couple of options
1) Generate the json in javascript
To do this you will need to create a simple page which includes a javascript JSON encoder (such as https://github.com/douglascrockford/JSON-js). This would be hosted at "/getStuff/index.html" and would be called by typing "www.mysite.com/getStuff/?arg=val..." For example:
<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//this function will take the window.location.search string of ?name=val and
//create an object like {'name':'val'}
var parseUrl = function(urlParams) {
var retObj = {};
var urlParameters = null;
if (!urlParams || urlParams.length == 0) {return retObj}
if (urlParams.charAt(0) == '?') {
urlParameters = urlParams.substring(1);
}else {
urlParameters = urlParams;
}
if (urlParameters.length == 0) {return retObj}
var parameterPairs = urlParameters.split('&');
var x;
for (x in parameterPairs) {
var parameterPair = parameterPairs[x];
parameterPair = parameterPair.split('=');
retObj[parameterPair[0]] = parameterPair[1];
}
return retObj;
};
var createJson = function(){
var params = parseUrl(window.location.search);
//do work here
var retObj = {}; //suppose this is the result of the work
document.print(JSON.stringify(retObj)); //use the included JSON encoder
};
</script>
</head>
<body onload="createJson();">
</body>
</html>
2) Use an MVC framework
Every MVC framework in existance will give you access to the search params used in the page request. Some will require you to provide them in /function/arg1/arg2 style (so /getStuff/jerry/engineer/12345, in your case). Others use a more traditional /function/?argName=argVal... approach. Once you have the arguments, it is a trivial matter to write them to the page in JSON format (http://php.net/manual/en/book.json.php).
Decisions, Decisions
Personally, I would use the MVC method, as it requires the least running around to get the JSON you want. However, unless you are familiar with an MVC framework (such as cake) you will probably find the process of getting up and running to be a bit arduous - these frameworks are designed for serving page content and getting them to serve up JSON is not always clearly documented.
Use jquery to parse the URL by inserting this into a <script> tag before creating the json object. from link from LekisS
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name');
In a separate script tag create your json object. You will need to include the Json2.js plugin to convert objects to JSON. So include this script also before the JSON object creation.
Once you have the appropriate scripts and variables you can create a json object using those parameters as needed by calling them as shown at the bottom of the example using jquery. You can also look up which JSON conversion (i.e, to string or object) you want from the Json2.js script file.
Now we have everything inside a bunch of scripts but where do we get json object through URL calling?
So the answer is simple:
Create a simple html page with these scripts where the last script finally creates and returns the json. Upload to server and use URL parameters like
www.mysite.com/getStuff?para1=value¶2=value2 to get the json object.