无法从Python中的javascript解析json post

2024-06-01 07:32:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我从get请求收到的字符串:

{'company_code': u'ha', 'from-date': u'', 'to-date': u'', 'ledger_type': u'CLNT', 'cost_center': u'ALL', 'margin': u'wtmg'}

现在,我完全不知道该怎么办。我想让str['company\u code']给我“ha”作为输出。你知道吗

但即使我这么做了json.dumps文件()或加载(),我无法访问它。你知道吗

有什么帮助吗?你知道吗

编辑: 在从javascript客户端发送JSON字符串并json.dumps文件,我明白了:

{"company_code": "ha", "from-date": "", "to-date": "", "ledger_type": "CLNT", "cost_center": "ALL", "margin": "wtmg"}

这是一个字符串。我不知道从这里该怎么走。你知道吗


Tags: to字符串frommargindatetypecodeall
1条回答
网友
1楼 · 发布于 2024-06-01 07:32:12

给定的字符串不是有效的JSON。这似乎是repr的结果。你知道吗

>>> print(repr({'company_code': u'ha'}))
{'company_code': u'ha'}

JSON字符串应该用双引号(“”)包装。你知道吗

>>> print(json.dumps({'company_code': u'ha'}))
{"company_code": "ha"}

>>> import json
>>> json.loads('"a"')
u'a'
>>> json.loads("'a'")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

编辑根据问题编辑。你知道吗

使用^{}解码json字符串;然后使用^{}语法访问值。你知道吗

>>> encoded = '{"company_code": "ha", "from-date": "", "to-date": "", "ledger_type": "CLNT", "cost_center": "ALL", "margin": "wtmg"}'
>>> decoded = json.loads(encoded)
>>> decoded['company_code']
u'ha'

相关问题 更多 >