How to convert a of string to an array of object

Advertisements

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:

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'}]

Leave a ReplyCancel reply