0

I am trying save the Dictionary type of my data to the json file of txt file using python3.
Example the form of my data like this:

listdic = []
dic1 = {"id": 11106, "text": "*Kỹ_năng đàm_phán* , thuyết_phục"}
dic2 = {"id": 11104, "text": "*Ngoại_hình ưa_nhìn* , nhanh_nhẹn , giao_tiếp tốt"}
dic3 = {"id": 10263, "text": "giao_tiếp tốt"}

listdic.append(dic1)
listdic.append(dic2)
listdic.append(dic3)

enter image description here

And i want it be saved to my json file like this:

enter image description here

i readed some solution on internet and i tried:

f = open("job_benefits.json", "a", encoding= 'utf-8')

for i in listdic:
    i = json.dumps(i)
    f.write(i + '\n')
f.close()

but the result i have is like this:

enter image description here

and then i try to read file and this is my the result:

f = open("job_benefits.json", "r", encoding= 'utf-8')

listdic = f.readlines()
for i in listdic:
    print(i)

enter image description here

That not the way write and read the data to json file i want and some body can help to solve this case ??
Thank you very muck and sorry about my grammar !

  • 2
    Note that what you see are unicode escapes which are perfectly fine for JSON. Load the file as a JSON instead of plain text and you get the initial input. – MisterMiyagi Apr 19 '20 at 17:09
  • Does this answer your question? [Getting readable text from a large json file in python](https://stackoverflow.com/questions/60978856/getting-readable-text-from-a-large-json-file-in-python) – MisterMiyagi Apr 19 '20 at 17:12
  • @MisterMiyagi thank you so much ! – Khánh Đinh Ngọc Apr 19 '20 at 18:23
  • Does this answer your question? [Python JSON and Unicode](https://stackoverflow.com/questions/9693699/python-json-and-unicode) – lenz Apr 19 '20 at 19:17

1 Answers1

3

You are saving the file with the json module and reading it back as text, and not trying to decode the json data read. So, all characters escape-encoded to prevent information loss remain escape-encoded.

You can force json to ouptut utf-8 encoding, insteading of automatically escapping all non-ASCII characters by passing dumps or dump the ensure_ascii=False argument:

f = open("job_benefits.json", "a", encoding= 'utf-8')

for i in listdic:
    i = json.dumps(i, ensure_ascii=False)
    f.write(i + '\n')
f.close()

or decoding from JSON after you read your lines back:

import json 

f = open("job_benefits.json", "r", encoding= 'utf-8')

listdic = f.readlines()
for i in listdic:
    print(json.loads(i))
jsbueno
  • 99,910
  • 10
  • 151
  • 209