To get JSON data from Javascript file - javascript

I have a subject.js javascript file in which json data is stored:
Subject.js
Example:
Teacher = {
"Eng" : "English",
"Math" : "Maths",
"Sci" : "Science",
"SST" : "Social Studies",
"Hin" : "Hindi"
};
I want to read json data from this js file into another js file.
But I learnt that $.getJSON('filename.json', function(data) { is used to get data from json file but my json data is stored in js file. Can anyone tell me how to get started? I tried using getJson but can't get it to work.

There are two possibilities:
The file can just be included and use the teacher variable as if you ran the getJSON function.
The Teacher = and semi-colon at the end can be removed (verify it is a correct JSON structure) and save the file as .json. Assuming your server will send a JSON file, this should allow the file to be requested.

Remove the varibale declaration "Teacher =" and your js become a json content that can be called by $.getJSON

You simply need to include the file with your Teacher definition on the same page as your other JS file. Then you will have access to the variables defined in Subject.js. For instance:
<script src="Subject.js"></script>
<script>
console.log(Teacher.Sci)
</script>
would output Science to the javascript console.
JSON is not its own type in Javascript, it is simply a certain syntax for defining plain-old Javascript objects. JSON stands for JavaScript Object Notation. This is the JSON part of your example:
{
"Eng" : "English",
"Math" : "Maths",
"Sci" : "Science",
"SST" : "Social Studies",
"Hin" : "Hindi"
}
So when you set a variable equal to a JSON block as in your example, you are creating an object with those properties. As such, you can simply treat that JSON object like any other javascript object. The code you provided is the same as the following:
Teacher = new Object();
Teacher.Eng = "English";
Teacher.Math = "Maths";
Teacher.Sci = "Science";
Teacher.SST = "Social Studies";
Teacher.Hin = "Hindi";
$.getJSON, on the other hand, is used for converting a text file (or file output) in JSON notation into a javascript object, but that is not necessary in this case, as your JSON object is already created within the javascript code.

Related

JavaScript: read and write json file

I have generated json file from my consumer pact in javaScript. When it's generating json file it doesn't contain what I expect. So, now I want to add block to my json file which I don't know how to do? Can someone here help me with that? so, basically I want to read json then create block and then write into json and save data
"path": {
"dataType": "String",
"expression": "data/xml/${id}",
"key": "request"
}
Thanks,
As #Barmar pointed out you can simply parse your JSON text and modify it.
let yourJsonText = "{...}"; // read in your json however you want
let yourJson = JSON.parse(yourJsonText);
// then modify your object
yourJson.path.newAttr = "something you like";
// parse it back to a JSON string
let yourUpdatedJsonText = JSON.stringify(yourJson);

Reading JSON data from JS file

I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.
var acb_messages = {"messages": [{
"timestamp": 1475565742761,
"datetime": "2016-10-04 12:52:22 GMT+05:30",
"number": "VM-449700",
"id": 1276,
"text": "Some text here",
"mms": false,
"sender": false
}
]}
How can I parse it in Python and then how can I use it?
Two approaches that I would try if I were at your place -
Convert my .js file to .json file and then using method suggested by #Sandeep Lade.
Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by #rahul mr.
Here is how to achieve 2nd solution -
import json
with open('your_js_file.js') as dataFile:
data = dataFile.read()
obj = data[data.find('{') : data.rfind('}')+1]
jsonObj = json.loads(obj)
What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.
Hope this is what you are looking for.
Warning - Code works only if your js file contains js object only.
The options above are correct, but the JSON syntax in JS can be a little different than in Python:
example.js:
property.docs = {
messages: {
timestamp: 1475565742761,
datetime: "2016-10-04 12:52:22 GMT+05:30",
number: "VM-449700",
id: 1276,
text: "Some text here",
mms: false,
sender: false
}
};
Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?
The complete code should be:
import json
import demjson
with open('example.js') as dataFile:
data = dataFile.read()
json_out = data[data.find('{'): data.rfind('}')+1]
json_decode = demjson.decode(json_out)
print(json_decode)
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)
the above code will store will store your json data in a dictionary called data. You can then process the dictionary

How to set the value received from the response to .js or json file

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;

Pass JSON string to PHP and push to array

rookie here. I've searched and searched and still remain ignorant.
I am making an array of markers/info windows for a Google Maps API. Currently, I have succeeded in loading my markers from an external JSON file. JSON data looks like this: https://codedump.io/share/5XUwRzOFvREi/1/json-array
pathway ./json/Markers
{"Markers": [
{
"title" : "Meow Monestary",
"position" : {
"lat" : 40.5178,
"lng" : -122.6438
},
"posterContact" : {
"name" : "Mr Meowser",
"email" : "MrMeow#Couch.com",
"phone" : "(555)-202-3040",
"private" : true
},
"type" : "myResidence",
"ownerContact" : {
"name" : false,
"email" : false,
"phone" : false,
"private" : true
},
"description" : "Meow meow purrrrr. Dogs are not my favorite but they are my second favorite.",
"private" : true
},
I want users to be able to fill out a form containing all of this data and then push the new marker object into the JSON array. So far I have collected the form, created a Javascript object, and converted it to a JSON string like this...
function submitForm(){
//place form data into array
var formData = $("#shelterForm").serializeArray();
//build the javascript object using the values in the array
var shelter = {
title:formData[0].value,
position:{
lat:formData[1].value,
lng:formData[2].value
},
posterContact:{
name:formData[3].value,
email:formData[4].value,
phone:formData[5].value,
private:formData[6].value
},
type:formData[7].value,
ownerContact:{
name:formData[8].value,
email:formData[9].value,
phone:formData[10].value,
private:formData[11].value
},
description:formData[12].value,
private:formData[13].value
};
shelterString = JSON.stringify(shelter);
}
I'm sure there was an easier way to do this. If you feel inclined to go into this... GREAT!! My main issue though is that now I have my JSON string, but can't figure out how to push it into my array. I'm thinking maybe pass the string to PHP and write to file, or possibly ajax allows this?
Whether or not you use AJAX, you will still need a script on the server to save the data server side. Doing an AJAX request is more advanced than just a regular form POST, so I would recommend against it for a beginner.
Once the data is sent to PHP, you will need to store it. The most common way this would be done is with a database, typically MySQL. When the form is posted, you would get the data from the $_POST variable and store it as a new row in the database. Then, for the JSON file, rather than using a static file, you would point the maps to a PHP script for the external JSON file. That script would then query the database, assemble the data into an associative array with code very much like your javascript submitForm() function, and then call json_encode() to convert that array into a JSON string that it would then print. On the client side, you would not need your submitForm() function anymore.
If you don't want to mess around with a database, you can use a regular file on your server and have the PHP script modify that file. It is a little messier, though, and if you have an error in your script or the server loses power while writing the file, you could lose all your data, so I would recommend also setting up a daily backup if you have important data in the file. Also, you will have to take special precaution to not allow two different people to submit their updates at the same time, since having two processes writing to the same file concurrently will cause garbage data. Databases are built to be more resilient to these problems out of the box.
If you want to go the file route, you would probably still want to move the creation of the JSON into PHP. Your javascript relies on the exact indicies of the form elements, and is hard to read and maintain. In PHP, you would have something like:
$shelter = [
'title' => $_POST['shelter_title'],
'position' => [
'lat' => $_POST['shelter_latitude'],
'lng' => $_POST['shelter_latitude']
],
The $_POST keys are the name attributes from your form elements, which makes it much easier to maintain than using index numbers, which would have to be renumbered if you added or removed a form field.
Then, you would need to lock the json file to make sure that two processes don't try to update it at the same time
if (!flock($json_filename,LOCK_EX)) {
die('We are having trouble updating our records. Please try again later.');
}
//Now nobody else can write to the file until the script finishes or calls flock($json_filename, LOCK_UN) to release the lock
Then, we load the old JSON file, and update it with our new record:
$old_json = file_get_contents($json_filename); //get JSON data as string
$old_data = json_decode($old_json); //convert JSON data into PHP array
$new_data = array_push($old_data['Markers'], $shelter); //add the new shelter to PHP array
$new_json = json_encode($new_data); //convert the PHP array back to a JSON string
file_put_contents($json_filename, $new_json); //write the string to the file
//json file is updated, so now you can display a message, or redirect the user to a new page with header('Location: foo')
I haven't tested this code, so back up your JSON before trying this.
What you should be doing here, is to have a local json file to which the google map api would be pointed to and to add to that file using the html form with a php action where you would ingest the form data and add it to the json file.
<form action="addJson.php" method="post">
addJson.php (to get the general idea)
<?php
$localFile = 'json/Markers.json';
$data = [$_POST]; // reformat if required
$existing = json_decode(file_get_contents($localFile));
$all = array_merge($existing,$data);
file_put_contents($localFile,json_encode($all));
echo 'thanks for addition';
?>
And you can totally omit the javascript submitForm function.

Set Variable Equal to Object Stored In Another File (Javascript)

I have an object defined in a .js file, which is done via PHP on the server side.
I would like to know how to set a variable equal to this object, because the JS file doesn't actually define anything, it is just the object...
EX: (this is my .js file on my server)
{
"Title": {"Link" = "http://example.com", "img" = "http://imgurl.com"},
"Title2": {"Link" = "http://blahblah.com", "img" = "http://imgurl.com"}
}
This is what we call a JSON file. You can parse it with JSON.parse.
As for how to get the content of the file dynamically, you could use the JQuery function getJSON or work the AJAX yourself, but I don't know a lot about that.

Categories