简体   繁体   English

在python中打开无效的json文件

[英]open invalid json file in python

I have a file with such non-valid json data (it's cut for clarity): 我有一个包含此类无效 json数据的文件(为清楚起见,将其剪切):

[
{
  "orderID": 90,
  "orderDate": '2017-05-10',  #issue №1
  "clientName": "Mr. Bean",
  "clientPhoneN": "123-4567",
  "orderContents": [
    {
      "productID": 05,        #issue №2
      "productName": "Bicycle",
      "quantity": 1,
      "price": 8000
    },
    {
      "productID": 23,
      "productName": "helmet",
      "quantity": 2,
      "price": 1000
    }
  ],
  "orderCompleted": true
}
]

I tried to open it in python and transform it to list of dictionaries, but with no success. 我试图在python打开它并将其转换为词典列表,但没有成功。 Depending on the case I get different errors. 根据情况,我会得到不同的错误。 It will take too much space to outline all my attempts and their ending errors. 概述我的所有尝试及其结束错误将花费太多空间。

I have two issues here with the file: 我在文件中有两个问题:

issue №1 - single quotes in orderDate value. 问题№1- orderDate值中的单引号。 it results with : 结果为:

JSONDecodeError: Expecting value

issue №2 - zero leading productID . 发行№2-零领先productID It results with: 结果为:

JSONDecodeError: Expecting ',' delimiter

I can hardcode these issues, but I feel that it's not true pythonic way. 我可以对这些问题进行硬编码,但是我觉得这不是真正的pythonic方法。

Is there an option of "pretty" opening and converting this data file to list of dictionaries? 是否可以选择“漂亮”打开此数据文件并将其转换为词典列表?

Most probably I want to keep productID data typa as integer , but if it's impossible, str is ok too. 我很可能希望将productID数据的类型保持为integer ,但是如果不可能的话, str也可以。

Try demjson package: 试试demjson包:

from demjson import decode
decode("""[
{
  "orderID": 90,
  "orderDate": '2017-05-10',
  "clientName": "Mr. Bean",
  "clientPhoneN": "123-4567",
  "orderContents": [
    {
      "productID": 05,
      "productName": "Bicycle",
      "quantity": 1,
      "price": 8000
    },
    {
      "productID": 23,
      "productName": "helmet",
      "quantity": 2,
      "price": 1000
    }
  ],
  "orderCompleted": true
}
]""")

You'll get: 你会得到:

[{'clientName': 'Mr. Bean',
  'clientPhoneN': '123-4567',
  'orderCompleted': True,
  'orderContents': [{'price': 8000,
    'productID': 5,
    'productName': 'Bicycle',
    'quantity': 1},
   {'price': 1000, 'productID': 23, 'productName': 'helmet', 'quantity': 2}],
  'orderDate': '2017-05-10',
  'orderID': 90}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM