I am working on parsing a text file having list of json paths from which I want to construct JSON.
This is how I am started.
def construct_json(jpath):
tokens = jpath.strip().split('.')
json = ''
for token in tokens:
if len(token.split('=')) == 2:
json = json + '"' + token.split('=')[0] +'"' + ':' + '"' + token.split('=')[1] + '"}}}}'
else:
json = json + '"'+token+'":{'
return '{'+json
jpaths_text = 'quiz.sport.q1.question=Which one is correct team name in NBA?,quiz.sport.q1.question=Which one is correct team name in Soccer?'
jpaths = jpaths_text.split(',')
questions = []
for jpath in jpaths:
questions.append(construct_json(jpath))
print questions
Above program gives me following output:
['{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in NBA?"}}}}', '{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in Soccer?"}}}}']
What I want is all q1
in list. something like following:
{
"quiz": {
"sport": {
"q1": [{
"question": "Which one is correct team name in NBA?"
}, {
"question": "Which one is correct team name in Soccer?"
}]
}
}
}
Any help/clue will be appreciated. Thanks.
well if the structure will be the same structure as that Example then you can use something like this:
ls = ['{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in NBA?"}}}}',
'{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in Soccer?"}}}}']
d = {"quiz": {
"sport": {
"q1": []
}
}}
for dic in ls:
q1 = json.loads(dic).get('quiz').get('sport').get("q1")
d.get('quiz').get('sport').get('q1').append(q1)
print(d)
import json def extract_questions(jpaths_text): questions_path = 'quiz.sport.q1.question=' questions = { 'quiz': { 'sport': { 'q1': [], }, }, } for jpath in jpaths_text.split(','): if jpath.find(questions_path) == 0: questions['quiz']['sport']['q1'].append( jpath.replace(questions_path, '')) return questions jpaths_text = 'quiz.sport.q1.question=Which one is correct team name in NBA?,quiz.sport.q1.question=Which one is correct team name in Soccer?' questions = extract_questions(jpaths_text) questions_json = json.dumps(questions) print(questions_json)
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.