创建嵌套的JSON(python)

时间:2018-08-24 15:48:50

标签: json python-3.x

下面的代码获取我从各个网站提取的数据,并将这些数据写入JSON文件。我想为NLP项目(Unigram,Bigram,Trigrams)创建一个名为{nlp_description}的嵌套部分。

如何完成此任务?

json_data = {}
json_data['news_sites'] = []

json_data['news_sites'].append({
        'URL': website_href,
        'Title': website_title,
        'Snippet': website_snippet,
        'Description': website_description,
        'Unigrams': unigrams,
        'Bigrams': bigrams,
        'Trigrams': trigrams})

    with open('data.txt', 'w') as outfile:
        json.dump(json_data, outfile, ensure_ascii=False,indent=6)

我尝试这样做,但是失败了:

json_data['news_sites'].append({
        'URL': website_href,
        'Title': website_title,
        'Snippet': website_snippet,
        'Description': website_description,
        'nlp_description':
            ('Unigrams': unigrams,
             'Bigrams': bigrams,
             'Trigrams': trigrams)})

    with open('data.txt', 'w') as outfile:
        json.dump(json_data, outfile, ensure_ascii=False,indent=6)

1 个答案:

答案 0 :(得分:1)

nlp_description键表示为错误的元组。也许您要找的是这个

json_data['news_sites'].append({
    'URL': website_href,
    'Title': website_title,
    'Snippet': website_snippet,
    'Description': website_description,
    'nlp_description':(
        {
            'Unigrams': unigrams,
            'Bigrams': bigrams,
            'Trigrams': trigrams
        }
    )
})