Hick
Hick

Reputation: 36394

Not able to parse a json post from javascript in Python

This is the string I'm receiving from the get request:

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

But even if I do json.dumps() or loads() on it, I'm just not able to access it.

Any help?

Edit: After sending a JSON string from the javascript client, and taking a json.dumps, I get this:

{"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.

Upvotes: 1

Views: 549

Answers (1)

falsetru
falsetru

Reputation: 369034

The given string is not a valid JSON. It seems like a result of repr.

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

JSON string should be wrapped in double qutoe ('"').

>>> 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; then access the value using dict[key] syntax.

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

Upvotes: 1

Related Questions