Extracting boolean values embedded in string in Python

89 Views Asked by At

I ran a survey on Mechanical Turk, and the results were returned to me in a string formatted like this:

[{"Q1_option1":{"Option 1":true},"Q1_option2":{"Option 2":false},"Q2_option1":{"Option 1":true},"Q2_option2":{"Option 2":false}}]

I'm not the sharpest programmer out there, and I'm struggling with how to extract the boolean values from the string. I only need the "true" and "false" values in the order they appear.

I would really appreciate any help!

1

There are 1 best solutions below

1
Itai Dagan On

You can use the regular expression module re to extract the values

import re

string = '[{"Q1_option1":{"Option 1":true},"Q1_option2":{"Option 2":false},"Q2_option1":{"Option 1":true},"Q2_option2":{"Option 2":false}}]'

bool_vals = re.findall("true|false", string)

print(bool_vals)

bool_vals is a list that contains the values in the order they appeared in your input string.