How to Convert Raw JavaScript Object to a Dictionary

How to convert raw javascript object to a dictionary?

demjson.decode()

import demjson

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = demjson.decode(js_obj)

jsonnet.evaluate_snippet()

import json, _jsonnet

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = json.loads(_jsonnet.evaluate_snippet('snippet', js_obj))

ast.literal_eval()

import ast

# from
js_obj = "{'x':1, 'y':2, 'z':3}"

# to
py_obj = ast.literal_eval(js_obj)

How to convert JavaScript dictionary into Python syntax

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.

Parsing javascript data structure in python

demjson.decode()

import demjson

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = demjson.decode(js_obj)

jsonnet.evaluate_snippet()

import json, _jsonnet

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = json.loads(_jsonnet.evaluate_snippet('snippet', js_obj))

ast.literal_eval()

import ast

# from
js_obj = "{'x':1, 'y':2, 'z':3}"

# to
py_obj = ast.literal_eval(js_obj)

Converting string to javascript dictionary

Please correct your JSON string,

Valid json is:  {"content":{"path":"callie/circle","type":"file"},"video":{"videoId":"CvIr-2lMLs‌​k","endSeconds":"30","startSeconds":15}}

Then convert string to JSON as:

var obj = JSON.parse(string);

What I tried:

var obj = JSON.parse('{"content":{"path":"callie/circle","type":"file"},"video":{"videoId":"CvIr-2lMLs‌​k","endSeconds":"30","startSeconds":15}}');
console.log(obj.content);
var obj2 = obj.content;
console.log(obj2.path);>>callie/circle

Convert a javascript list to dictionary

Of course this doesn't work.

It does (if we fix the typo in Let and we assume you wanted an array of three objects), you're just not using the result:

    let list = ['cat', 'rabbit', 'fish']
// vvvvvvv list = list.map(x => { return({animal: x}); }); console.log(list);

Convert string to dict without using split in Python Scrapy

My approach is to first add the quotes surrounding the keys to make that string into a valid JSON string, then convert:

import json
import re

data = '{clientId: "300",id: "new",ctime: "6/3/2022",mtime: "6/3/2022"}'

valid = re.sub(r"(\w+):", r'"\1":', data)
# '{"clientId": "300","id": "new","ctime": "6/3/2022","mtime": "6/3/2022"}'

json_object = json.loads(valid)
# {'clientId': '300', 'id': 'new', 'ctime': '6/3/2022', 'mtime': '6/3/2022'}

Notes

  • The regular expression (\w+): matches the keys
  • In r'"\1":', the \1 part stands for the matched text in the above.


Related Topics



Leave a reply



Submit