2

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 !

4
  • 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. Commented Apr 19, 2020 at 17:09
  • Does this answer your question? Getting readable text from a large json file in python Commented Apr 19, 2020 at 17:12
  • @MisterMiyagi thank you so much ! Commented Apr 19, 2020 at 18:23
  • Does this answer your question? Python JSON and Unicode Commented Apr 19, 2020 at 19:17

1 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.