How can I specify encoding of string that comes from server side?

2144 views javascript
8

I am relatively new to web dev and even not familiar when it comes to front end side. I got a problem regarding encoding issue.

  • environment : python 2.7 , Flask

I send a json data at server like this.

@app.route("/test")
def test():
    data = json.dumps({"name": "???", "id": "gildong1"}, ensure_ascii=False)
    return render_template("testpage.html", data=data)

I printed out data at server side and it prints Korean character just fine.

But whenever I receive the data at javascript like this,

var t_data = JSON.parse({{data}});

The result at console is like this.

var t_data = JSON.parse({"name": "???", "id": "gildong1"});

answered question

1 Answer

12

You can encode the response in the server side to

convert your line

`data = json.dumps({"name": "???", "id": "gildong1"}, ensure_ascii=False)` 

to

`data = json.dumps({"name": "???", "id": "gildong1"}, ensure_ascii=False).encode('utf8')`

OR

Handle this on the client side using regex to replace all occurrence of " to "

var input = '{"name": "???", "id": "gildong1"}'
input = input.replace(/(")/g,'"');
console.log(input); // {"name": "???", "id": "gildong1"}

posted this

Have an answer?

JD

Please login first before posting an answer.