简体   繁体   English

无法在Python中解析来自javascript的json帖子

[英]Not able to parse a json post from javascript in Python

This is the string I'm receiving from the get request: 这是我从get请求接收的字符串:

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

Now, I'm completely confused what to do with this. 现在,我完全不知道该怎么办。 I want to make str['company_code'] give me "ha" as output. 我想让str ['company_code']给我“ ha”作为输出。

But even if I do json.dumps() or loads() on it, I'm just not able to access it. 但是,即使我在上面执行json.dumps()或load(),我也无法访问它。

Any help? 有什么帮助吗?

Edit: After sending a JSON string from the javascript client, and taking a json.dumps, I get this: 编辑:从javascript客户端发送JSON字符串,并接受json.dumps后,我得到以下信息:

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

which is a string. 这是一个字符串。 I'm not sure how to go forward from here. 我不确定如何从这里继续前进。

The given string is not a valid JSON. 给定的字符串不是有效的JSON。 It seems like a result of repr . 似乎是repr的结果。

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

JSON string should be wrapped in double qutoe ('"'). 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

EDIT according to the question edit. 根据问题编辑编辑

Use json.loads to decode the json string; 使用json.loads解码json字符串; then access the value using dict[key] syntax. 然后使用dict[key]语法访问该值。

>>> 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'

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

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