I have a string like this which is retrieved from a database. I need to convert the string to a Javascript dictionary.
"['content':{'type':'file','path':'callie/circle'},'video':{'videoId':'CvIr-2lMLsk','startSeconds': 15,'endSeconds': 30'}]".
How do I convert the above string to a Javascript dictionary? Should I convert the string to json first or not? When I try json.parse
, an error is shown:
Uncaught SyntaxError: Unexpected token '
at Object.parse (native)
at :2:6
at Object.InjectedScript._evaluateOn (:905:140)
at Object.InjectedScript._evaluateAndWrap (:838:34)
at Object.InjectedScript.evaluate (:694:21)
To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.
Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.
You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.
A dictionary is a general-purpose data structure for storing a group of objects. A dictionary has a set of keys and each key has a single associated value. When presented with a key, the dictionary will return the associated value.
Please correct your JSON string,
Valid json is: {"content":{"path":"callie/circle","type":"file"},"video":{"videoId":"CvIr-2lMLsk","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-2lMLsk","endSeconds":"30","startSeconds":15}}');
console.log(obj.content);
var obj2 = obj.content;
console.log(obj2.path);>>callie/circle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With