1

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.

1
  • Can you please precise in your question in which direction the data is going? I guess you have a javascript client and python server. You sent data in JSON format from python to javascript but you did not use json.dumps and that's why python is issuing it's unicode special u"" formatting. Is that right? Commented Jan 11, 2014 at 16:31

1 Answer 1

1

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'
Sign up to request clarification or add additional context in comments.

7 Comments

Anyway I could parse it then?
@Hick, You can use ast.literal_eval in Python: decoded = ast.literal_eval(the_given_string). It will works as long as it only contains str, unicode, int, float, ...
Or maybe I could try to send json from the javascript client.
@Hick, Yes, that is better than using ast.literal_eval.
@Hick, But, it seems like the string is originated from Python. (Do you see u prefix in the string literal?). You should dump json in Python part.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.