首页 > 解决方案 > 使用包含 html、转义字符和换行符的文件解析 Json

问题描述

我正在尝试将下面的 JSON 提取到 csv 文件中,由于转义字符,它无法解析字段“questionLBL”,\n,。我也尝试过替换,但没有太大帮助。

谁能帮我解析这个JSON?

{
   "question": {
       "active": true,
       "itemId": "746",
       "alternative": null,
       "searchTerm": null,
       "answer": "50000",
       "enumerationCodeDelimiters": null,
       "dataType": "String",
       "multiValued": false,
       "smId": "0778299",
       "workType": "REQUEST",
       "type": "External",
       "totalQuestions": "23",
       "Label": "Request Form",
       "questionLBL": "Request Type\n<em style=\"color: rgb(255, 0, 0); font-family: Arial, Verdana, sans-serif; font-size: 13px;\">If you are unsure which request type to use, please see the attached Reference file.</em>"
    }}

我尝试了许多其他方式的示例之一:

import json
import csv
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
with open("test_2020.json", "r") as rf:
    decoded_data = json.load(rf)

#print(decoded_data)
# Check is the json object was loaded correctly
try:
 with open("test.csv","w") as outfile:
    f = csv.writer(outfile,delimiter='|',quoting=csv.QUOTE_ALL)

    for i in decoded_data:
     
      f.writerow([i.get(("active"),"null"),i.get(("itemId"),"null"),i.get(("alternative"),"null")\
      i.get(("searchTerm"),"null") ,i.get(("answer"),"null"),\
      i.get(("enumerationCodeDelimiters"),"null"),i.get(("dataType"),"null"),i.get(("multiValued"),"null"),\
      i.get(("smId"),"null"),i.get(("workType"),"null")\
      i.get(("type"),"null"),\
      i.get(("totalQuestions"),"null"),i.get(("Label"),"null"),i.get(("questionLBL"),"null"),\
      ])


except KeyError:
      print("Error Found")

标签: pythonjson

解决方案


推荐阅读