1

I am receiving a response from a service in text format unfortunately I cannot ask them to send me in JSON format) below is the reponse:

'{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}'

I want to either convert this to dict or json but I am unable to do so, as the string inside the '{ }' does not have single or double quotes.

I have tried using json.loads(), json.dumps(), ast.literal() and also few other methods, but was not able to achieve the desired output.

The output desired is:

{'message': 'Successfully sent data for processing', 'execId' : 'd03c96hg-4098-47b9-9e4b-3cb2c' }
3
  • what you have tried ? Commented Feb 7, 2018 at 6:11
  • @VikasDamodar I have tries json.load('{message: hello how are you, exceID: abc123-tyhx}') but throws me an error. Also tried ast.literal('{message: hello how are you, exceID: abc123-tyhx}') Commented Feb 7, 2018 at 6:17
  • I have made an attempt solve your issue, you can check in answers. Commented Feb 7, 2018 at 6:24

3 Answers 3

2

With a bit of string manipulation you can convert like:

Code:

def my_convert(a_string):
    convert = a_string.replace(
        ': ', '": "').replace(
        '}', '"}').replace(
        ', ', '", "').replace(
        '{', '{"')

    return json.loads(convert)

Test Code:

import json
data = '{message: Successfully sent data for processing, ' \
       'execId: d03c96hg-4098-47b9-9e4b-3cb2c}'

print(my_convert(data))

Results:

{'message': 'Successfully sent data for processing', 'execId': 'd03c96hg-4098-47b9-9e4b-3cb2c'}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your prompt response but there is a small catch, there are two key 'message' and 'execId', but as the above code I get only message key.
1
data = '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}'
// actual string message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c

    data_str = data[1:-1]
    t_arr = data_str.split(',')
    data_dict = {}
    for data in t_arr : 
        temp = data.split(':')
        data_dict[str(temp[0].strip())] = str(temp[1].strip())

    print data_dict 

Comments

1

Here a code you can try, Don't know pythonic or not :

g = '{message: Successfully sent data for processing, execId: d03c96hg-4098-47b9-9e4b-3cb2c}'
a = []
for i in g.split(","):
    a.append(i.strip("{}").split(":"))
b = {}
for j in a:
   b.update({j[i]: j[i+1] for i in range(0, len(j), 2)})
print(b)

it will give the o/p like this :

{'message': ' Successfully sent data for processing', ' execId': ' d03c96hg-4098-47b9-9e4b-3cb2c'}

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.