I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/
Related
I am using the karate api framework to automate web services.
Currently, I am facing problem to set the response value back to the .js or JSON file which I receive from the cucumber feature file.
My response:{"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001'}
How can I save this to .js or JSON file to reuse them in other scripts [feature files] ?
Thanks in advance.
You cannot save the value to a .js or JSON file provided you don't want to write the value to a json file
You can assign the value to a variable , let say using a namespacing technique to avoid collision
var nameSpaceObject = {
authKey : "",
someOtherFunctionIfNecessary :function(){}
};
Then you can call this name space & assign value to it
var response = {"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001' }
nameSpaceObject.authKey = response.authorizationtoken;
i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')
I'm creating an android app which takes in some json data, is there a way to set up a directory such as;
http://......./jsons/*.json
Alternatively, a way to add into a json file called a.json, and extend its number of containing array data, pretty much add more data into the .json file this increase its size.
It could be by PHP or Javascript.
Look into Parsing JSON, you can use the JSON.parse() function, in addition, I'm not sure about getting all your JSON files from a directory call, maybe someone else will explain that.
var data ='{"name":"Ray Wlison",
"position":"Staff Author",
"courses":[
"JavaScript & Ajax",
"Buildinf Facebook Apps"]}';
var info = JSON.parse(data);
//var infostoring = JSON.stringify(info);
One way to add to a json file is to parse it, add to it, then save it again. This might not be optimal if you have large amounts of data but in that case you'll probably want a proper database anyway (like mongo).
Using PHP:
$json_data = json_decode(file_get_contents('a.json'));
array_push($json_data, 'some value');
file_put_contents('a.json', json_encode($json_data));
I query the db i my model like so
function graphRate($userid, $courseid){
$query = $this->db->get('tblGraph');
return $query->result();
}
My controller gets data back from my model and I json encode it like so
if($query = $this->rate_model->graphRate($userid, $courseid)){
$data['graph_json'] = json_encode($query);
}
$this->load->view('graph', $data);
And thats returns me a json object like so
[
{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
]
In my view graph I'm loading an js file
<script type="text/javascript" src="script.js"></script>
Now I want to use $data that is being sent from my controller to my view, to my external script.js to use as labels and data to feed my chart. But How do I get that Json data to my external script.js so I can use it?
1 more thing about the json data, isn't it possible to get the output of the json data as
{
"obj1":{"id":"1","title":"myTitle","score":"16","date":"2013-08-02"},
"obj2":{"id":"2","title":"myTitle2","score":"17","date":"2013-09-02"},
"obj3":{"id":"3","title":"myTitle3","score":"18","date":"2013-10-02"}
}
The problem isn't a Codeigniter problem, it's a javascript scope/file inclusion/where-do-i-get-my-data-from problem.
I run into this all the time and have used these solutions:
naming my php files with .php extensions and loading them as if they're views.
Just putting the script that needs data from a view IN the view file where it's used
Using an ajax request in my included js file to hit a controller and get json data.
I use #2 most frequently (for things like datatables where I WANT the js code right there next to the table it's referencing.
I use #1 occasionally, but try NOT to do that because it means some .js files are in my webroot/js dir and some are in teh application/views directory, making it confusing for me or anyone else who wants to support this project.
#3 is sometimes necessary...but I like to avoid that approach to minimize the number of requests being made and to try to eliminate totally superfluous requests (which that is).
You need to print the result of the output json string to the html generated file.
But you need to parse the string with some script. I would recommend you: http://api.jquery.com/jQuery.parseJSON/
For the second question. It is possible by doing:
$returnValue = json_encode(
array (
"obj1" => array("id"=>"1","title"=>"myTitle","score"=>"16","date"=>"2013-08-02"),
"obj2" => array("id"=>"2","title"=>"myTitle2","score"=>"17","date"=>"2013-09-02"),
"obj3" => array("id"=>"3","title"=>"myTitle3","score"=>"18","date"=>"2013-10-02"),
)
);
Print the output using PHP like:
echo json_encode($query);
Then from the client-side (where JavaScript resides) load that JSON that you printed using PHP. This can be done easily using JQuery.
Like this:
$.get("test.php", function(data) {
alert("Data Loaded: " + data);
});
You can find more information about this here: http://api.jquery.com/jQuery.get/
Now you'll need to parse this data so that JavaScript can understand what you got as text from the server. For that you can use the JSON.parse method on the "data" object in the aforementioned example. Once parsed, you can use the object like any other object in JavaScript. You can find more information about JSON.parse here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
I hope that helps.
I want to create dynamic array from server data,
For example,
I need format in the following way:
["project1","project2","project3"]
This is my code
var arrayVal = [];
for(var i=0;i<project.name;i++){
//array generation
}
project1,project2,.... are getting from server.
What you're looking for is JSON.parse. Here's an example copied form the JS terminal.
> a = JSON.parse('["project1","project2","project3"]')
["project1", "project2", "project3"]
> a[0]
"project1"
Now, be weary, JSON isn't integrated to all browsers yet. You can download a JSON script to emulate the native functions. See here and here