如何从JPATH构造JSON

时间:2019-07-27 15:00:17

标签: python json

我正在解析一个文本文件,该文件包含要从其构造JSON的json路径列表。

这就是我的开始方式。

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

上面的程序给了我以下输出:

['{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in NBA?"}}}}', '{"quiz":{"sport":{"q1":{"question":"Which one is correct team name in Soccer?"}}}}']

我想要的是列表中的所有q1。类似于以下内容:

{
    "quiz": {
        "sport": {
            "q1": [{
                "question": "Which one is correct team name in NBA?"
            }, {
                "question": "Which one is correct team name in Soccer?"
            }]
        }
    }
}

任何帮助/线索将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:1)

如果结构与示例相同,那么您可以使用如下代码:

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)

答案 1 :(得分:1)

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)