当前位置: 动力学知识库 > 问答 > 编程问答 >

python - how to extract a list of lists (containing any value type) from json

问题描述:

From a mobile client, we're sending a list of lists as part of a json to the server(python 2.7). This needs to be split into individual lists for processing.

Example json = {"table":"[[1,2,3],[2,3,4],....]"}

What I need is to extract individual lists [1,2,3],[2,4,5] etc, add an extra object at the start of the list and insert them into a postgres DB.

For extracting the json I use :

post_data = json.loads(request.data)

table = post_data['table']

print table prints u'[[1,2,3],[2,3,4]]'.

I checked a couple of questions and use the following snippet for processing and inserting into db.

tbl = post_data['table']

table = ast.literal_eval(tbl)

print table

tup_table = []

for lst in table :

lst.insert(0,userid)

tup_table += [tuple(lst)]

connection = engine.raw_connection()

cur = connection.cursor()

records_list_template = ','.join(['%s'] * len(tup_table))

insert_query = 'insert into stats(userid,rid,val,fid) values {0}'.format(records_list_template)

cur.execute(insert_query, tup_table)

connection.commit()

connection.close()

The problem however is ast.literal_eval() works fine in this example but does not work when the list in json contains values of other types. For e.g when the list is [[1,abc,3],[2,bcd,4]] it returns an error ValueError('malformed string')

I've tried using table.encode('utf-8') instead. That returns a list type but the for loop loop does not extract a sub-list and it extracts each character in the list separately.

Is there a better way of extracting a list from the unicode and fetching the sublist for creating the tuple ?

网友答案:

Like your error message indicates, the given json file is malformed. You forgot the quotes.

Change [[1,abc,3],[2,bcd,4]] to [[1,"abc",3],[2,"bcd",4]].

分享给朋友:
您可能感兴趣的文章:
随机阅读: