-1

I am loading a json file from an API and the data contain Chinese characters, when I just print the result, the characters are perfectly decdoded.

token = "xxxxxxx"
headers = {"Authorization": "Bearer " + token}
apiurl = "https://api.wmcloud.com/data/v1//api/market/getMktBlockd.json?"
param = {
    "beginDate": "",
    "endDate": "",
    "secID": "",
    "ticker": "",
    "assetClass": "",
    "tradeDate": "20190308",
}
r = requests.get(apiurl, params=param, headers=headers)

dataresult = json.loads(r.text)

print(dataresult)

but if I want to print with this function, the characters are again encoded.

print(json.dumps(dataresult, indent=2))

Output is like

"buyerBD": "\u534e\u6cf0\u8bc1\u5238\u80a1\u4efd\u6709\u9650\u516c\u53f8\u6dee\u5b89\u5206\u516c\u53f8",

I have this command at the beginning of my code:

# -*- coding: utf-8 -*-

Why does two functions output different results, how to resolve?

Many thanks.

AKX
  • 152,115
  • 15
  • 115
  • 172
L.Li
  • 3
  • 2
  • The `coding:` comment has absolutely no meaning for the strings your program processes, it just tells Python the encoding of the program's sources. With Python 3, UTF-8 is the default, so you don't need to declare it. – tripleee Mar 11 '19 at 08:48
  • Because that's how Chinese (can) look(s) encoded in JSON…!? – deceze Mar 11 '19 at 08:48

1 Answers1

0

Switch ensure_ascii off in json.dumps:

import json

x = {"\u534e": "\u6cf0"}
print(json.dumps(x, indent=2, ensure_ascii=False))

outputs

{
  "华": "泰"
}
AKX
  • 152,115
  • 15
  • 115
  • 172