简体   繁体   中英

Extracting boolean values embedded in string in Python

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM