简体   繁体   中英

python code to convert input data into json format variable

I have a input variable(stud_id), list(sub_code) and array(data) with the below values.

stud_id: 10

sub_code: ['002', '003', '007']

data: [array([['867192', '5545']], dtype=object), array([['964433', '0430']], dtype=object), array([['965686', '2099']], dtype=object)]

How to convert the above input into json format like this? stud_id is the main key

output =       '{ "10" : { "002" : [ 867192, 5545 ], '\
               '           "003" : [ 964433, 0430  ], '\
               '           "007" : [ 965686, 2099 ] } }'

I had to adjust your array type for testing.

Try this code:

stud_id = 10

sub_code = ['002', '003', '007']

#data = [array([['867192', '5545']], dtype=object), 
#        array([['964433', '0430']], dtype=object), 
#        array([['965686', '2099']], dtype=object)]

data = [['867192', '5545'], 
        ['964433', '0430'], 
        ['965686', '2099']]


output =       '{ "10" : { "002" : [ 867192, 5545 ], '\
               '           "003" : [ 964433, 0430  ], '\
               '           "007" : [ 965686, 2099 ] } }'
               
dd = {str(stud_id):{k:a for k,a in zip(sub_code, data)}}

print(dd)

Output

{'10': {'002': ['867192', '5545'], '003': ['964433', '0430'], '007': ['965686', '2099']}}
>>> import json >>> from numpy import array >>> stud_id = 10 >>> sub_code = ['002', '003', '007'] >>> data = [array([['867192', '5545']], dtype=object), ... array([['964433', '0430']], dtype=object), ... array([['965686', '2099']], dtype=object)] >>> json.dumps({stud_id: dict(zip(sub_code, map(lambda arr: arr[0].tolist(), data)))}) '{"10": {"002": ["867192", "5545"], "003": ["964433", "0430"], "007": ["965686", "2099"]}}'

Zip sub_code and data , turn them into a dict with a dict comprehension, then put them in another dictionary with stud_id as a key, then dump as json:

import json

json.dumps({stud_id: {k: v.tolist()[0] for (k, v) in zip(sub_code, data)}})
# '{"10": {"002": ["867192", "5545"], "003": ["964433", "0430"], "007": ["965686", "2099"]}}'

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