venkatama
venkatama

Reputation: 75

Multiline Json not working with python json.loads

This is the python request code

response = requests.post(jobsurl, data=searchPayload, auth=(user, password), verify=validateCert)
    print(response.text)

which returns the following string

{"preview":false,"offset":0,"result":{"title":"testalert1","eai:acl.owner":"testorphanuser","request.ui_dispatch_app":"search","splunk_server":"host1","qualifiedSearch":"search index=_internal | head 1"}}
{"preview":false,"offset":1,"lastrow":true,"result":{"title":"testalert2","eai:acl.owner":"testorphanuser","request.ui_dispatch_app":"search","splunk_server":"host1","qualifiedSearch":"search index=_internal | head 2"}}

I'm trying to do json.load and getting error

job_data = json.loads(response.text)
    print(job_data)
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 212)

I'm trying to parse title, eai:acl.owner and request.ui_dispatch_app, I guess the error is from second json line entry. is there a way I can load them and append to a list?

any help would be greatly appreciated

Upvotes: 0

Views: 1246

Answers (1)

venkatama
venkatama

Reputation: 75

As json.loads() is not working for multi line json entries for me and getting error at second entry. I wrote the output to a file and looped each line to do json.loads() as @klaus mentioned, which worked. not sure if there is another easy way but this worked for me.

data = response.text
with open('data.txt', 'w') as wf:
    wf.write(data)
with open('data.txt') as rf:
    for entry in rf:
        entryDist = json.loads(entry)
        entryList.append(entryDist)

Upvotes: 1

Related Questions