json文件,value值中带英文引号导致报错

json文件,value值中带英文引号导致报错

json文件,value值中带英文引号导致报错

举例说明:

  {
    "id": 1,
    "context": "Xiao Li was admitted to Tsinghua University, or Xiao Sun failed to enter Peking University.",
    "question": "Which of the following conditions should be added to conclude that "Xiao Li was admitted to Tsinghua University"?",
    "A": "At least one of Xiao Zhang and Xiao Li failed to enter Tsinghua University.",
    "B": "Both Xiao Zhang and Xiao Sun have been admitted to Peking University.",
    "answer": "B"
  },
  {
    "id": 2,
    "context": "If it is an unchangeable fact that you can't have your cake and eat it, then either of the following must also be true ",
    "question": "Is it a fact?",
    "A": "Get a "fish" but not a bear's paw.",
    "B": "If you get a "fish", you don't get a bear's paw.",
    "answer": "B"
  }

报错如图所示:
报错如图所示
修改方法:

将英文引号改为中文引号 (也有其他方法,我自认为这是最笨的方法)

首先

读取文件(txt或json格式文件)

import os
import re

f = open("aaa.json", "r", encoding='utf-8')
i = 0     #id
j = 0     
while True:
    line = f.readline()
    if line:
        i = i + 1   #id = 1 第一条数据
        line=line.strip()   #读取每一行的数据存为line,line是字符串
        if i % 8 == 4:   #一条数据有8行内容,第4行
            line = line[:13] + re.sub('"', '“' , line[13:-2]) + '",'    #question
            #我只想修改value值里面的英文引号,所以替换sub函数范围为value值范围
        elif i % 8 == 5:
            line = line[:6] + re.sub('"', '“', line[6:-2]) + '",'  # A
        elif i % 8 == 6:
            line = line[:6] + re.sub('"', '“', line[6:-2]) + '",'  # B
        print(line)
    else:
        break
f.close()

运行结果

{
"id": 1,
"context": "Xiao Li was admitted to Tsinghua University, or Xiao Sun failed to enter Peking University.",
"question": "Which of the following conditions should be added to conclude that “Xiao Li was admitted to Tsinghua University“?",
"A": "At least one of Xiao Zhang and Xiao Li failed to enter Tsinghua University.",
"B": "Both Xiao Zhang and Xiao Sun have been admitted to Peking University.",
"answer": "B"
},
{
"id": 2,
"context": "If it is an unchangeable fact that you can't have your cake and eat it, then either of the following must also be true ",
"question": "Is it a fact?",
"A": "Get a “fish“ but not a bear's paw.",
"B": "If you get a “fish“, you don't get a bear's paw.",
"answer": "B"
}