0

I am relatively new to web development and even less familiar when it comes to the front end side. I've got a problem regarding an encoding issue.

  • environment: python 2.7, Flask

I am sending json data to a 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 the data on the server side and it prints Korean characters just fine.

But whenever I receive the data in javascript like this:

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

The result in the console is like this:

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

Update

I am suspicious of the content-type header. When I inspected it through the debugger, I found that the Content-Type header is u'text/html'. So I tried to change my code like this, but it still prints unicode:

@app.route("/test")
def test():
    data = json.dumps({"name":"홍길동", "id": "gildong1"}, ensure_ascii=False).encode("utf8")
    resp = make_response(render_template("TestPage.html", data=data))
    resp.headers['Content-Type'] = 'text/html'
    return resp
ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
JunKim
  • 647
  • 7
  • 17

2 Answers2

0

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"}
front_end_dev
  • 1,998
  • 1
  • 9
  • 14
  • Thanks, but isn't there any default option in javascript on which encoding I can choose? – JunKim Nov 04 '18 at 05:54
  • convert your line `data = json.dumps({"name": "홍길동", "id": "gildong1"}, ensure_ascii=False)` to `data = json.dumps({"name": "홍길동", "id": "gildong1"}, ensure_ascii=False).encode('utf8')` – front_end_dev Nov 04 '18 at 05:58
  • @KimHyungJune I have update the answer. You can do this in your server side while doing `json.dumps` call – front_end_dev Nov 04 '18 at 06:00
  • Actually, I also tried your suggestion earlier but the result was same. – JunKim Nov 04 '18 at 06:21
0

Have you tried jsonify() instead of json.dumps()? See here and this little piece of code

from flask import Flask, jsonify, json
app = Flask(__name__)
data = json.dumps({"name":"홍길동", "id": "gildong1"})
with app.app_context():
  data2 = jsonify(name="홍길동", id= "gildong1")
print (data)
print(data2.get_json())
# output
# {"id": "gildong1", "name": "\ud64d\uae38\ub3d9"}
# {'id': 'gildong1', 'name': '홍길동'}
scraaappy
  • 2,830
  • 2
  • 19
  • 29