0

I'm building a Flask app with a Treant.js tree. In this example the tree diagram takes data like so

    lana = 
    {
        text: {name: "lana"},
        image: "static/images/lana.png",
        parent: malory
    }

That works fine. I now need to recreate that from a Python object

Right now I have

d = {}
d["parent"] = "malory"
d["text"] = { 'name': "lana" }
d['image'] = 'static/images/stripe.png'
print json.dumps(d)

>>> {"text": {"name": "lana"}, "image": "static/images/stripe.png", "parent": "malory"}

Also, when I log it to the console in the browser I get the same result.

Which does not work. All of the keys have quotes around which seems to cause the issue. How do I remove the quotes around the keys.

Ben Mayo
  • 1,285
  • 2
  • 20
  • 37

2 Answers2

1

The problem is not about quotes. It's rather about data to code conversion. On the client, you need to have valid JavaScript code to execute. Usually, the code is static, while the data it works with is dynamically generated by the server. Such data is usually provided in the form of JSON objects. And JSON looks similar to JavaScript, but it's not a JavaScript code. However, JavaScript supports JSON as a native way to represent data.

Example:

<!-- your template -->
<script>
    var myVar = {{ my_flask_var|json }};
    console.log(myVar);
</script>

In the example above, the response from the server will look like:

<!-- your template -->
<script>
    var myVar = {"foo": 42, "bar": "qux"};
    console.log(myVar);
</script>

However, it's valid JavaScript.

Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90
0

I believe you may be confusing JavaScript objects and JSON strings. Your tree library is expecting a JavaScript object. You'll need to convert your JSON string into one.

In JSON, keys must be strings, and strings in JSON are defined as

a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes

So removing those double quotes would result in invalid JSON. What you need to do it parse it to create a JavaScript object:

let s = '{"text": {"name": "lana"}, "image": "static/images/stripe.png", "parent": "malory"}';
let o = JSON.parse(s);
cody
  • 11,045
  • 3
  • 21
  • 36