-3

When I extract some data from a data-source the data is getting extracted as a string object and the json is being exported as a string.

I have tried

json.loads() -> link1 Convert string to JSON in Python? and this convert a json string to python object from other answers.

However, the expectation is

"details": 
"{
'col1': 'col1_details',
'col2': 'col2_details',
'col3': 'col3_details'
}"

the expected outcome is

details":
{
'col1': 'col1_details',
'col3': 'col2_details',
'col3': 'col3_details'
}

as you see the extra quotes are causing the json to be read as a string and json.loads() and json.dumps() are not working.

I am open to any suggestions without using regex to create a json object directly/easily?

edit:

modified the string object - and the whole point as you see is that the data extraction process is creating a string instead of creating a json object bypassing an extra "" that makes it an invalid json object where I cannot use json.loads and json.dunps and hence the question.

7
  • Does this answer your question? Convert string to JSON in Python? Commented Jul 13, 2022 at 17:59
  • 2
    That isn't valid JSON. Make a minimal reproducible example. What is the exact content of the data object? Commented Jul 13, 2022 at 18:00
  • No. It does not. I already tried that solution. Commented Jul 13, 2022 at 18:01
  • 2
    @Vyas your expected output is not a valid JSON format Commented Jul 13, 2022 at 18:04
  • Invalid JSON. Please first verify JSON with a validator. Also, this question just presents some output, without giving the input. Not really that handy... You also seem to have two different expectations. Commented Jul 13, 2022 at 18:04

1 Answer 1

1

Assuming you meant

"details": {
  'col1': 'col1_details',
  'col3': 'col2_details',
  'col3': 'col3_details'
}

Then re-loads the data

data["details"] = json.loads(data["details"])

But, this assumes whatever response you've gotten actually returns valid JSON, which single-quotes are not (there might be a good reason it is returned as a string instead)

Therefore, the most reasonable solution would be to modify the code that returned that response, not try to fix it via parsing it at a later point.

Sign up to request clarification or add additional context in comments.

4 Comments

that's probably not going to work because data["details"] seems to be a Python repr not a JSON
well, it isn't the only solution, you can eval the string back to a Python object, since it seems simple enough
Or ast.literal_eval?
sure, either one would work (assuming the OP's example data is representative of the actual data)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.