2

I have an output that contains system output information from a remote server, and at the very end of the output, it contains a JSON object. Like this:

output:

...
-Verification-
-Test1: PASS
-Test2: PASS
...
...
Result: PASS
...
#JSON Object below
{"path": "/my/path/file.log",  "name": "Roger", "year": 2018}

The output would only contain one set of {} and that is the JSON object I want to parse. So we don't have to worry about grabbing wrong information

I would like my flask app to parse this output to only return the JSON object (everything in the {} including the {}) and filter all the text above it. How can I do this?

1
  • Did you tried using regex ? Commented Jul 19, 2018 at 0:12

3 Answers 3

2
import re
jsonstr='''...
-Verification-
-Test1: PASS
-Test2: PASS
...
...
Result: PASS
...
#JSON Object below
{"path": "/my/path/file.log",  "name": "Roger", "year": 2018}'''
print(jsonstr.lstrip(re.sub('{.*}','',jsonstr)))

jsonstr='''...
-Verification-
-Test1: PASS
-Test2: PASS
...
...
Result: PASS
...
#JSON Object below
{"path": "/my/path/file.log",  "name": "Roger", "year": 2018}'''
print([i for i in jsonstr.splitlines() if i.startswith('{') and i.endswith('}')])
Sign up to request clarification or add additional context in comments.

Comments

1

Use regex (re) with expression {.*}

Comments

0

To locate the JSON string, since you know there are no other '{'s in it, use str.find and string indexing:

json_loc = jsonstr.find('{')
if json_loc >= 0:
    jsonstr = jsonstr[json_loc:]
else:
    raise Exception("no JSON string found")

Comments

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.