Reputation: 19329
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"
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'}
Upvotes: 1
Views: 3013
Reputation: 19329
While 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"})
Upvotes: 0
Reputation: 27423
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.
Upvotes: 1
Reputation: 9858
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'}
Upvotes: 3