Use JSON.parse method
<script>
var bgjson = {{BgDict|tojson|safe}};
console.log(jQuery.type(bgjson));
console.log(JSON.parse(bgjson)[4]);
</script>
Answer from Rafał on Stack OverflowI have a flask quiz game that uses a dictionary created whenever another script is imported. The way the game works is that as the player makes an incorrect guess, more information is revealed until they get it right or run out of info.
I want to now send the data in the Python dictionary to javascript so that I can set each key-value pair to be hidden and reveal one pair everytime the player gets the answer wrong. I know I should probably use json for this but whenever I use something like
{{dictname | tojson}}I get a property assignment error. Also i’ve tried converting the python dict to json in the app using json.dumps, but I don’t know how to directly access it in the javascript.
How can I convert Python dictionary to JavaScript hash table? - Stack Overflow
python - How to convert a dictionary into a javascript object - Stack Overflow
Convert django/python dict via json to javascript dict - Stack Overflow
json - Convert python dictionary to JavaScript object literal - Stack Overflow
Python and javascript both have different ideas about how to represent a dictionary, which means that you need a intermediate representation in order to pass data between them. The most common way to do this is JSON, which is a simple lightweight data-interchange format.
Use the python json library to convert (or dump) your python dict into a JSON string. Then in the javascript parse the JSON string into a javascript dict. (If you are using JQuery, then use jQuery.parseJSON)
You could convert it to JSON and use that in that template
In your python code do
import json
...
...
return {'parameters': json.dumps(parameters)} #This data goes into your template
In Python:
import json
send_to_js = json.dumps({
"name": "Paul",
"age": "20",
"gender": "male"
})
Then in JavaScript:
JSON.parse(send_to_js)
// result is {name: 'Paul', age: '20', gender: 'male'}
In the end I did it using regex:
def saveFile(dictionary, fileName):
jsonStr = json.dumps(dictionary, indent=4, ensure_ascii=False);
removeQuotes = re.sub("\"([^\"]+)\":", r"\1:", jsonStr);
fileNameCleaned = fileName.split(" ")[0]
with open(fileNameCleaned + ".ts", "w",encoding='utf_8') as outfile:
outfile.write("export const " + fileNameCleaned + " = " + removeQuotes + ";")
@Rubik, I may guess, alert() takes a string as parameter and you're passing it an object in second call to alert().
JSON.parse() creates an object from the string representation of any object (array, set etc.).
Please try to change your JS code as follows (just modify 2 lines):
Please comment if it doesn't work, I will update my answer to help you.
$(".dict").click(function () {
alert("first alert");
// var result = JSON.parse(jsonheaderdict);
alert(JSON.stringify(jsonheaderdict));
});
» Try below sample code for verification.
var jsonheaderdict = {"F 1": ["BBBB", "AAAAA"], "F 2": ["ASDASD"], "F 3": ["QWEQWE"]};
console.log(jsonheaderdict);
alert(jsonheaderdict)
alert(JSON.stringify(jsonheaderdict))
It is important to recognize that you are not passing a value from Python to JavaScript, you are writing JavaScript source code using Python.
This…
jsonheaderdict = {"F 1": ["BBBB", "AAAAA"], "F 2": ["ASDASD"], "F 3": ["QWEQWE"]}
… is the JavaScript syntax to assign an object (created with an object literal) to jsonheaderdict.
It isn't JSON. It isn't a string. It makes no sense to put it anywhere near JSON.parse.
Just use the object directly.
Further reading: There's no such thing as a "JSON Object"
If you know all your keys are valid tokens you can use this simple code:
Copyimport json
def js_list(encoder, data):
pairs = []
for v in data:
pairs.append(js_val(encoder, v))
return "[" + ", ".join(pairs) + "]"
def js_dict(encoder, data):
pairs = []
for k, v in data.iteritems():
pairs.append(k + ": " + js_val(encoder, v))
return "{" + ", ".join(pairs) + "}"
def js_val(encoder, data):
if isinstance(data, dict):
val = js_dict(encoder, data)
elif isinstance(data, list):
val = js_list(encoder, data)
else:
val = encoder.encode(data)
return val
encoder = json.JSONEncoder(ensure_ascii=False)
js_val(encoder, {'height': 100, 'title': 'some great title'})
The return value of js_val() is in your desired format.
Dirty hack, but could work: subclass JSONEncoder and override _iterencode_dict method, so that it yields key formatted as you want. In python3.3 it is in line 367 of json.encoder module in line yield _encoder(key). You probably want to copy the whole method and change this line to something like yield key if isinstance(key, str) else _encoder(key).
Again - this is really dirty, unless you have no other option - don't do that. Though, it is doable, what is worth knowing if you really need it.
Remove export default when reading the file, and add it back when writing.
with open("abc.js") as f:
contents = f.read()
contents = contents.replace('export default', '')
data = json.loads(contents)
data['Country'] = 'Italy'
new_contents = 'export default' + json.dumps(data)
with open("abc.js", "w") as f:
f.write(new_contents)
You can also extract JSON data from your js file, merge it with your Python dictionary, and write it back to the file.
import json
with open("abc.js","r") as file:
contents = file.read()
json_object = json.loads(contents[contents.index("{"):])
countries = {"Country":"Italy"}
merged_object = {**json_object, **countries}
with open("abc.js","w") as file:
file.write("export default " + json.dumps(merged_object, indent = 4))
Hello all,
I'm going through 100 Days of Python and reading "Introducing Python" by O'Reilly one thing that bothers me is the dict (insert funny joke). But seriously, what's the difference between a dict and a JSON object in JavaScript? Is there really any difference or should I just treat them as the same?
Kind regards
demjson.decode()
import demjson
# from
js_obj = '{x:1, y:2, z:3}'
# to
py_obj = demjson.decode(js_obj)
chompjs.parse_js_object()
import chompjs
# from
js_obj = '{x:1, y:2, z:3}'
# to
py_obj = chompjs.parse_js_object(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)
Use json5
import json5
js_obj = '{x:1, y:2, z:3}'
py_obj = json5.loads(js_obj)
print(py_obj)
# output
# {'x': 1, 'y': 2, 'z': 3}