Reading an Exported Javascript Object in Python - javascript

Is it possible to read/parse an exported Javascript or Typescript JSON-like object in Python?
For example:
In myJava.js:
export const myObj = {
entry: val
entry2: val2
...
}
In parseJava.py:
def parseJava():
# Some code to read in the javascript object
javaObjAsDictionary = someFunction("myJava.js")
Does such a "someFunction()" exist? If not, are there any clean ways around this?
Thanks in advance!

If you want to parse JSON, there is a library called JSON in Python 2 and 3 that does the encoding and decoding.
Specifically, you can use the json.loads or json.load methods to get a Python object (dictionary/list) from your JSON.
Something like:
import json
jsonDict = json.load("myJSON.json")
I am not sure exactly if this is what you need, hope this gives you a start.

# following code assumes that 'data.json' file exists in the current working directory
with open('data.json', 'r') as jsonFile: # opens JSON file in read only mode
# loads the content of JSON file and converts it into python dictionary object
dictionary = json.load(jsonFile)
print(dictionary)

Related

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

Getting Variables from a external .json file Python

What I need help with
I want to receive variables from a external .json file in the local directory
using python27
(import doesn't work)
I want to store the variables in the .json like below
value1 = "this_is_value1"
value2 = "this_is_value2"
value3 = "this_is_value3"
and have them being used in a script.
If I can get it to the point of which the .json includes
value1 = "this_is_value1"
and my .py includes
print(value1)
with output
>>>this_is_value1
I can take it from there
My end Task
The idea is that I need to change specific parts of another .yaml file, this program needs to take variables like (ID, System_id, IP) and for this case I need a .json I can change which the python27 script then pulls the information from to change the .yaml file.
I've done this part fine, just need to do this part
Have I researched the issue?
In short, YES.
however, theses answer use .py or other file types.
I've already tried importing the file but since it needs to sit next to the script I can't use import
Other anwser simply give no information back about how they solved the issue.
With a json formatted file (say "my_file.json"), for instance:
{
"x": "this is x",
"y": "this is x",
"z": "this is z"
}
Then in Python:
import json
with open("my_file.json", "r") as f:
my_dict = json.load(f)
print(my_dict["x"])
Yields:
this is x
I generally like to control this process with a method or function. Here is a code snip I use frequently that will read the format of the text file you've shown:
class MainApp(object):
def __init__(self, config_file):
# Initialization stuff from a configuration file.
self.readConfigFile(config_file)
def readConfigFile(self, file):
try:
with open(file, 'r') as cfg:
lines = list(cfg)
print("Read", len(lines), "lines from file", file)
# Set configured attributes in the application
for line in lines:
key, value = line.split('=')
setattr(self, key.strip(), value.strip())
except:
print('Configuration file read error')
raise
if __name__ == '__main__':
# Create an instance of the application.
# It will read the configuration file provided here.
app = MainApp('myconfig.txt')
# Now you can access the attributes of the class (read from config file)
print(app.value1, app.value2, app.value3)
This should work:
>> string1 = 'value1 = "this_is_value1"'
>> exec(string1)
>> print(value1)
"this_is_value1"
If what you really need is a .txt file, then I recommend you to take a look at the documentation:
https://docs.python.org/3/tutorial/inputoutput.html
Go to section: 7.2 Reading and Writing a file
Basically, you'll need is:
lines = [] # for further data manipulation
file = open("c:\path\to\your.txt", "r")
for line in file:
lines.append([line.split("=")])
file.close()
Now if you have in your .txt bar="foo"
Then in the lines list you can do:
lines[0][0] # output "bar"
lines[0][1] # output "foo"
Of course there are some more smater way of doing this, but this is just basic idea.

Import JSON with mongo script

I'm trying to write a mongo script to import a jsonArray from a JSON file. My script is in .js format and I execute it with load() command in mongo shell. Is it possible to do it with a mongo script?
I know I can use mongoimport instead. But I want to know a way to do it with a script.
The contents of my current script in which the import part is missing is given below..
var db = connect("localhost:27017/fypgui");
//Import json to "crimes" collection here
var crimes = db.crimes.find();
while (crimes.hasNext()){
var item = crimes.next();
var year =(item.crime_date != null)?(new Date(item.crime_date)).getFullYear():null;
db.crimes.update( {_id: item._id}, {$set: {crime_year: year}});
}
There is another answer to this question. Even though it's a bit old I am going to respond.
It is possible to do this with the mongo shell.
You can convert your JSON to valid JavaScript by prefixing it with var myData= then use the load() command to load the JavaScript. After the load() you will be able to access your data from within your mongo script via the myData object.
data.js
var myData=
[
{
"letter" : "A"
},
{
"letter" : "B"
},
{
"letter" : "C"
}
]
read.js
#!/usr/bin/mongo --quiet
// read data
load('data.js');
// display letters
for (i in myData) {
var doc = myData[i];
print(doc.letter);
}
For writing JSON is easiest to just load your result into a single object. Initialize the object at the beginning with var result={} and then use printjson() at the end to output. Use standard redirection to output the data to a file.
write.js
#!/usr/bin/mongo --quiet
var result=[];
// read data from collection etc...
for (var i=65; i<91; i++) {
result.push({letter: String.fromCharCode(i)});
}
// output
print("var myData=");
printjson(result);
The shebang lines (#!) will work on a Unix type operating system (Linux or MacOs) they should also work on Windows with Cygwin.
It is possible to get file content as text using undocumented cat() function from the mongo shell:
var text = cat(filename);
If you are interested cat() and other undocumented utilities such as writeFile are defined in this file: shell_utils_extended.cpp
Having file's content you can modify it as you wish or directly pass it to JSON.parse to get JavaScript object:
jsObj = JSON.parse(text);
But be careful: unfortunately JSON.parse is not an equivalent of mongoimport tool in the sense of its JSON parsing abilities.
mongoimport is able to parse Mongo's extended JSON in canonical format. (Canonical format files are created by bsondump and mongodump for example. For more info on JSON formats see MongoDB extended JSON).
JSON.parse does not support canonical JSON format. It will read canonical format input and will return JavaScript object but extended data type info present in canonical format JSON will be ignored.
No, the mongo shell doesn't have the capability to read and write from files like a fully-fledged programming environment. Use mongoimport, or write the script in a language with an official driver. Node.js will have syntax very close to the mongo shell, although Node.js is an async/event-driven programming environment. Python/PyMongo will be similar and easy to learn if you don't want to deal with structuring the logic to use callbacks.
Hey I know this is not relevent but, every time I need to import some jsons to my mongo db I do some shity copy, paste and run, until I had enough!!!
If you suffer the same I v written a tiny batch script that does that for me. Intrested?
https://github.com/aminjellali/batch/blob/master/mongoImporter.bat
#echo off
title = Mongo Data Base importing tool
goto :main
:import_collection
echo importing %~2
set file_name=%~2
set removed_json=%file_name:.json=%
mongoimport --db %~1 --collection %removed_json% --file %~2
goto :eof
:loop_over_files_in_current_dir
for /f %%c in ('dir /b *.json') do call :import_collection %~1 %%c
goto :eof
:main
IF [%1]==[] (
ECHO FATAL ERROR: Please specify a data base name
goto :eof
) ELSE (
ECHO #author amin.jellali
ECHO #email a.j.amin.jellali#gmail.com
echo starting import...
call :loop_over_files_in_current_dir %~1
echo import done...
echo hope you enjoyed me
)
goto :eof

How do I encode/decode a file correctly after reading it through javascript and pass the file data through ajax?

I have a django File field with multiple attribute set to true. I am trying to make a multiple file uploader where I get the file objects with a simple javascript FileReader object. After looping through the file list I read the file data through
reader.readAsBinaryString(file);
and get the desired file data result. After passing this data to my views through ajax I am trying to create a copy of the file into the media folder. I am presently using the following views function :
#csrf_exempt
def storeAttachment(data):
'''
stores the files in media folder
'''
data = simplejson.loads(data.raw_post_data)
user_org = data['user_org']
fileName = data['fileName']
fileData = data['fileData']
file_path = MEDIA_ROOT + 'icts_attachments/'
try:
path = open((file_path+ str(user_org) + "_" + '%s')%fileName, "w+")
path.write(fileData)
path.close()
return HttpResponse(1)
except IOError:
return HttpResponse(2)
I am able to write simple text files,.js,.html and other few formats but when I try to upload pdf, word, excel, rar formats I get the following error in my response even though a file with invalid data is saved at my MEDIA path(the file does not open).
'ascii' codec can't encode characters in position 41-42: ordinal not in range(128)
I tried to encode/decode the file data using various references but with no effect..Any advice will be greatly appreciated..
You got error because Python 2's default ASCII encoding was used. Characters greater than 127 cause an exception so use str.encode to encode from Unicode to text/bytes.
Good practice is to use with keyword when dealing with file objects.
path = u''.join((file_path, user_org, '_', fileName)).encode('utf-8')
with open(path, 'w+') as f:
f.write(fileData)

Read JavaScript variables from a file with Python

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database.
For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this:
title: Script title
alias: script_alias
I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this:
var title = "Script title";
var alias = "script_alias";
Is it possible to read these variables with Python easily?
Assuming you only want the two lines, and they are at the top of the file...
import re
js = open("yourfile.js", "r").readlines()[:2]
matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
matches = matcher_rex.match(line)
if matches:
name, value = matches.groups()
print name, value
Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Categories

Resources