-1

I have flask variable called 'gene_info' which is json object and I want to access one index in json for example 'gene_info['AMPH']'. 'AMPH' is a variable value in JavaScript. So how can I do this?

var symbol = 'AMPH'; var td_name = '{{ gene_info[' $symbol '] | tojson }}'; console.log(td_name);

  • You can't. JavaScript is executed in the browser, not on your server where Flask runs. Flask produces text data for the browser to read and find JavaScript code in. The browser then executes the JavaScript code. Either put the whole `gene_info` data structure into the HTML page you generate so the JavaScript code can have access to it, or use a Python variable to select the specific entry in `gene_info` to put in the page. – Martijn Pieters Apr 27 '20 at 17:32

1 Answers1

-2

1) Using JSON.parse

var symbol = 'AMPH';
var td_name = JSON.parse("{{ gene_info[' $symbol '] | tojson }}"); // WARN: XSS potential injection
console.log(td_name);

or 2) inline <script/>

<script>{{ gene_info[' $symbol '] | tojson }}</script>
// ...
var symbol = 'AMPH';
var td_name = window.td_name_json;
console.log(td_name);

or, the best, 3) offer it via other path

@GET
def serve_json():
    import json
    return json.dumps($symbol) # or jsonpickle or simplejson

if third case keep in mind you might need JavaScript's fetch or other XHR request like library (jquery, axios)

test30
  • 3,496
  • 34
  • 26
  • There is not really a need to use `JSON.parse()` because Flask's `tojson` outputs JSON that is a strict subset of JavaScript. You can use `td_name = {{ gene_info | tojson }};` directly. You **can't** however use `'$symbol'`, there is no such key in the `gene_info` dictionary. – Martijn Pieters Apr 27 '20 at 17:34
  • `$symbol` is also not a valid Python identifier or expression, so option 3 fails too. Returning a `json.dumps()` string is also *not going to work*, Flask has dedicated tools to produce JSON responses, please use those. – Martijn Pieters Apr 27 '20 at 17:36
  • I fail to see how the inline script would work, because all that the `tojson` filter will produce is a string that's valid JSON. Where is `td_name_json` going to come from? – Martijn Pieters Apr 27 '20 at 17:37
  • Another issue I see: why the *WARN: XSS potential injection* label on the first option, but not the second or 3rd? They are just as vulnerable to the issue, provided the attacker produces their attack *inside* of the JSON data structure, *and* the JavaScript code in the page then uses that data unescaped. The technique in and of itself does *not* pose a specific XSS risk. – Martijn Pieters Apr 27 '20 at 17:39
  • all of those solutions might lead to XSS... I've just mentioned it in the first one – test30 Apr 27 '20 at 20:27