Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to javascript dictionary

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)

like image 562
Mubashir Kp Avatar asked Aug 08 '15 12:08

Mubashir Kp


People also ask

How do I convert a string to a dictionary?

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.

Can you make a dictionary in JavaScript?

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.

Can we convert string to dictionary in Python?

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.

What is a dictionary JavaScript?

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.


1 Answers

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
like image 182
MrYo Avatar answered Oct 09 '22 02:10

MrYo