Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a of string to an array of object

I have a string which contains values in some format (it is the output of an sql query). The string format is like this : 'enable id \n =============\nf avc-qwqwq\nt abd-rrtrtr\n f rec-yyuyu \n')

So, the first 2 values are the column names of the sql and the rows are inside the \n values. So, I have 2 extract these values and pass it as an object.So, I am able to get the values in a list, but can’t figure out how to pass these values as an object.

My code looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result = ('enable id \n =============\nf   avc-qwqwq\nt abd-rrtrtr\n f rec-yyuyu \n')
n=2
r = result.split('\n')
newlist = r[n:]
print('r', newlist)      //Output : r ['f   avc-qwqwq', 't abd-rrtrtr', ' f rec-yyuyu ', '']

Now, how to make an object which looks like:

[{
 'enable':'f',
 'org':'avc-qwqwq'
},
{
'enable':'f',
 'org':'abd-rrtrtr'
},
{
'enable':'f',
 'org':'rec-yyuyu'
}]

>Solution :

text = ('enable id \n =============\nf   avc-qwqwq\nt abd-rrtrtr\n f rec-yyuyu \n')

# Extract first two rows.
header_str, _, *rows_str = text.splitlines()

# Parse field names from headers' row.
header = header_str.split()

# Create list of objects mapping words to respective field names from header.
objs = [dict(zip(header, row_str.split())) for row_str in rows_str]

print(objs)
# [{'enable': 'f', 'id': 'avc-qwqwq'}, {'enable': 't', 'id': 'abd-rrtrtr'}, {'enable': 'f', 'id': 'rec-yyuyu'}]

This assumes your row values are separated by whitespace. If not, you’ll have to change the row_str.split() part to extract field values from a row.


Here’s a Python 2-compatible version:

text = ('enable id \n =============\nf   avc-qwqwq\nt abd-rrtrtr\n f rec-yyuyu \n')

iter_lines = iter(text.splitlines())

# Extract first two rows.
header_str = next(iter_lines)
_ = next(iter_lines)
rows_str =list(iter_lines)

# Parse field names from headers' row.
header = header_str.split()

# Create list of objects mapping words to respective field names from header.
objs = [dict(zip(header, row_str.split())) for row_str in rows_str]

print(objs)
# [{'enable': 'f', 'id': 'avc-qwqwq'}, {'enable': 't', 'id': 'abd-rrtrtr'}, {'enable': 'f', 'id': 'rec-yyuyu'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading