On 2015-05-28 00:51, Karthik Sharma wrote:
I tried modifying the program as follows as per your suggestion.Doesn't seem to 
work.

import simplejson as json
import cjson

json_input = { "msgType": "0",
     "tid": "1",
     "data": "[{\"Severity\":\"warn\",\"Subject\":\"Reporting 
\",\"Message\":\"tdetails:{\\\"Product\\\":\\\"Gecko\\\",\\\"CPUs\\\":8,\\\"Language\\\":\\\"en-GB\\\",\\\"isEvent\\\":\\\">
     "Timestamp": "1432703193431",
     "Host": "myserver.com",
     "Agent": "Experience",
     "AppName": "undefined",
     "AppInstance": "my_server",
     "Group": "UndefinedGroup"
}

print('json input original  {} \n\n'.format(json_input))

data = json_input['data']

print('data {} \n\n'.format(data))

message = json.loads(data)

print('message {} \n\n'.format(message['Message']))

I get the following error.

Traceback (most recent call last):
   File "test_json.py", line 23, in <module>
     print('message {} \n\n'.format(message['Message']))
TypeError: list indices must be integers, not str
karthik.sharma@aukksharma2:~$ vim test_json.py

You have a different error message now. It says that 'message' is a
list.

Have a look at the JSON data. It represents a list that contains a dict.


On Thursday, 28 May 2015 11:14:44 UTC+12, Cameron Simpson  wrote:
On 27May2015 15:23, Karthik Sharma <karthik.sha...@gmail.com> wrote:
>I have the JSON structure shown below and the python code shown below to 
manipulate the JSON structure.
>
>    import json
>
>    json_input = {
>        "msgType": "0",
>        "tid": "1",
>        "data": "[{\"Severity\":\"warn\",\"Subject\":\"Reporting 
\",\"Message\":\"tdetails:{\\\"Product\\\":\\\"Gecko\\\",\\\"CPUs\\\":8,\\\"Language\\\":\\\"en-GB\\\",\\\"isEvent\\\":\\\">
>        "Timestamp": "1432703193431",
>        "Host": "myserver.com",
>        "Agent": "Experience",
>        "AppName": "undefined",
>        "AppInstance": "my_server",
>        "Group": "UndefinedGroup"
>    }
>
>
>    data = json_input['data']
>    tdetails = data['Message']
>    print('json_input {} \n\ndata {} \n\n tdetails 
{}\n\n'.format(json_input,data,tdetails))
>
>I am getting the error.
>
>    Traceback (most recent call last):
>      File "test_json.py", line 19, in <module>
>        tdetails = data['Message']
>    TypeError: string indices must be integers, not str

That will be because of this line:

  tdetails = data['Message']

because "data" is just the string from your dict.

>The JSON structure is valid as shown by http://jsonlint.com/
>   I want to be able to access the different fields inside `data` such as 
`severity`, `subject` and also fields inside `tdetails` such as `CPUs` and 
`Product`. How do I do this?

Then you need to decode "data". Example (untested):

  data_decoded = json.loads(data)

and then access:

  data_decoded['Message']


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to