python中argsparse_在python中使用argparse解析整个JSON

我试图使用ARGPARSE库在一个简单的参数中解析整个Json,但事实是,当它碰到子内部的不同元素(例如“-”和“”)时,它会突然停止。

这是测试代码:

#parse.py

import argparse

parser = argparse.ArgumentParser(description='JSON_test')

parser.add_argument('-contenido', action='store', dest='CONTENIDO',

help='JSON content')

args = parser.parse_args()

C = args.CONTENIDO

print (C)

这是运行代码的示例

python parse.py -contenido """{"desde": "2020-03-01","hasta": "2020-03-31","plantas": [{"id": 6,"nombre": "MDS","inversores": [{"id": "Ingeteam 0237","energa": 2152.8070,"pr": 61.5299,"disponibilidad": 81.1770,"factorPlanta": 15.5313}, {"id": "Ingeteam 0538","energa": 2167.5898,"pr": 61.9315,"disponibilidad": 81.0459,"factorPlanta": 15.6381}, {"id": "Ingeteam 0236","energa": 2168.1885,"pr": 61.9511,"disponibilidad": 80.9856,"factorPlanta": 15.6426}, {"id": "Ingeteam 0563","energa": 2206.8702,"pr": 63.0825,"disponibilidad": 80.9455,"factorPlanta": 15.9219}]"""

最后是错误

parse.py: error: unrecognized arguments: 0237,energia: 2152.8070,pr: 61.5299,disponibilidad: 81.1770,factorPlanta: 15.5313}, {id: Ingeteam 0538,energia: 2167.5898,pr: 61.9315,disponibilidad: 81.0459,factorPlanta: 15.6381}, {id: Ingeteam 0236,energia: 2168.1885,pr: 61.9511,disponibilidad: 80.9856,factorPlanta: 15.6426}, {id: Ingeteam 0563,energia: 2206.8702,pr: 63.0825,disponibilidad: 80.9455,factorPlanta: 15.9219}]"

我们的体系结构不允许我们使用文件进行解析,因此无法解决:(。我该怎么办?我读了很多SOF帖子,明天我将对其进行测试,但我认为它们不会起作用。为了适应此特定问题,我们的json非常大,我们需要从单个参数运行它。

解决方案

使用一个单引号引起来的命令行参数,而不是三重双引号。三重双引号是Python语法,而不是Shell语法。

python parse.py -contenido '{"desde": "2020-03-01","hasta": "2020-03-31","plantas": [{"id": 6,"nombre": "MDS","inversores": [{"id": "Ingeteam 0237","energa": 2152.8070,"pr": 61.5299,"disponibilidad": 81.1770,"factorPlanta": 15.5313}, {"id": "Ingeteam 0538","energa": 2167.5898,"pr": 61.9315,"disponibilidad": 81.0459,"factorPlanta": 15.6381}, {"id": "Ingeteam 0236","energa": 2168.1885,"pr": 61.9511,"disponibilidad": 80.9856,"factorPlanta": 15.6426}, {"id": "Ingeteam 0563","energa": 2206.8702,"pr": 63.0825,"disponibilidad": 80.9455,"factorPlanta": 15.9219}]'

您还可以使用一个双引号将参数引起来,但是您需要对参数中的每个双引号进行转义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值