Writing out javascript dictionary from inside of JavaScript- enabled application (such as Adobe) into external .jsx file (using dict.toSource()) the context of resulted dictionary looks like:
({one:"1", two:"2"})
(Please note that dictionary keys are written as they are the variables name (which is not true).
A next step is to read this .jsx file with Python. I need to find a way to convert ({one:"1", two:"2"}) into Python dictionary syntax such as:
{'one':"1", 'two':"2"}
It has been already suggested that instead of using JavaScript's built-in dict.toSource() it would make more sense to use JSON which would write a dictionary content in similar to Python syntax. But unfortunately using JSON is not an option for me. I need to find a way to convert ({one:"1", two:"2"}) into {'one':"1", 'two':"2"} using Python alone. Any suggestions on how to achieve it? Once again, the problem mostly in dictionary keys syntax which inside of Python look like variable names instead of strings-like dictionary keys names:
one vs "one"
EDITED LATER:
Here is the content of the output.txt file as a result of JavaScript dictionary exported from inside of JaveScript. The goal is to read the content of output.txt file into Python and convert it to Python dictionary.
Please keep in mind that the dictionary is only here that simple. In real world scenario it will be a MegaByte long with many nested keys/values.
Once again, the content of output.txt:
({one:"1", two:"2"})
We need to transform it into Python syntax dictionary (it is fine if we use JSON if it is used in Python):
{'one':'1', 'two':'2'}
3 Answers 3
One of the comments suggested using demjson. This does indeed work and seems a better solution.
import demjson
demjson.decode('{one:"1", two:"2"}')
Outputs:
{u'two': u'2', u'one': u'1'}
2 Comments
With trivial objects containing no enclosed objects, this is a basic string manipulation problem.
As soon as you have a compound object, the code I'll show you will fail.
Let's fire up Python 2.7 and use your example string:
>>> x='({one:"1", two:"2"})'
Now what you want is a dict d...
What do we know about dict?
Well, a dict can be made from a list of (key, value) "2-ples", by which I mean a list of two element lists as opposed to a list of python tuple read-only lists.
Each tuple is a representation of a property like one:"1"
First, we need to reduce x to a substring that contains the desired information.
Clearly the parenthesis and brackets are superfluous, so we can write:
>>> left = x.find("{")
>>> right = x.find("}")
>>> y = x[left+1:right]
Here, the String.find() method finds the first index of the search string parameter.
The notation x[n:m] is a substring of the n-th through the m-1st character of x, inclusive.
Obtaining:
>>> y
'one:"1", two:"2"'
That's just a string, not a tuple, but it can be made a tuple if we split on comma.
>>> z = y.split(",")
Obtaining:
>>> z
['one:"1"', ' two:"2"']
Now each of these strings represents a property, and we need to tease out the key and value.
We can use a list comprehension (see tutorial 5.1.4 if unfamiliar) to do that.
>>> zz = [ (s[0:s.find(":")].strip(),s[s.find('"')+1:-1].strip()) for s in z]
Where once again we use find() to get the indexes of the colon and quote.
Here we also use strip() to strip out the whitespace that will otherwise creep in.
This step obtains:
>>> zz
[('one', '1'), ('two', '2')]
Which is almost what we wanted.
Now just
d = dict(zz)
And it is done!
>>> d
{'two': '2', 'one': '1'}
Note that dict does not preserve the order of keys.
12 Comments
x is just a string. It can't be a dict, because, as you noticed, it is in the wrong format for python to accept it as a dict.json built in module, that might have been more robust. OP didn't want that or something happened. When I came back those answers were deleted. Some of the question comments may be insightful.JSON if it is used from inside of Python to read the dictionary in (since Python supports JSON natively. Please outline how it could be achieved from inside Python. If let's say I have a text file as a result of 'JaveScript` dictionary export... How do I use JSON module in Python to read JavaScript exported dictionary into Python: Once again here is how JavaScript writes to output (export) file using myDict.toSource(): ({one:"1", two:"2"}) The main problem is that dictionary keys don't have quotes characters making them (the dict keys) appear like variables nameWhile working in JavaScript I've noticed that its built-in .toSource() method will write key dictionary properly enclosed in quotes "dict key name" if that dictionary key includes a non-letter character in its name such as a white space, comma, period, a dollar sign and etc. Example:
Example JavaScript:
var dictVar = {'one':'1','.two':'2', 'three,':3, 'fo ur':4,"five":"five"};
mySaveFile = new File('/my/path/to/JavaDictToPython.txt');
mySaveFile.open("w","TEXT","????");
mySaveFile.write(dictVar.toSource());
mySaveFile.close();
A dictionary will be written to file as:
({one:"1", ".two":"2", "three,":3, "fo ur":4, five:"five"})
import json{'one':"1", 'two':"2"}is valid as either a Python Dict or a Javascript Object.JavaScriptdictionary out to the file supportsJavaScript. It does not supportJSON. Sure,JSONmodule can be copied to /This App/script/ folder. But that would have to be repeated on each and every machine running this app. It is exactly what I want to avoid. By all mean the code should be kept all "stock". No plugin, addons or module outside of default install please. It was mentionedJSONcannot be used as a solution. Why to re-ask it again? The solution can be found using stockJavaScriptor stockPython. Thanks for the comment.