使用Python从Json提取数据的问题

时间:2019-02-07 01:14:43

标签: python json line bots

我正在为LINE中的朋友构建一个机器人游戏。我是一个初学者。我正在尝试在json中调用一个包含字符串+整数的对象。我环顾四周,但似乎没有什么适合我的需求。最佳/简单的解决方案是什么?

我的代码是业余代码,请对我轻松一点。 :P 我正在尝试通过Json的“名称” +“状态”提取Python。 现在,它仅提取“名称”并随机选择一个项目。有什么方法可以选择项目+统计信息,显示项目并计算统计信息?谢谢。

Python 3:
if text == 'FIGHT':
    with open('items.json', 'r') as f:
        data = json.load(f)
        armor1 = [v for d in data['armor'] for k,v in d.items() if k == 'name']
        weapon1 = [v for d in data['weapon'] for k,v in d.items() if k == 'name']
        magic1 = [v for d in data['magic'] for k,v in d.items() if k == 'name']
        armor2 = random.choice(armor1)
        weapon2 = random.choice(weapon1)
        magic2 = random.choice(magic1)
        calc = add(int(armor2), int(weapon2), int(magic2))
        line_bot_api.reply_message(
            event.reply_token, 
                TextSendMessage('Armor = ' + (armor2)),
                TextSendMessage('Weapon = ' + (weapon2)),
                TextSendMessage('Magic = ' + (magic2)),
                TextSendMessage('You have a score of ' + str(calc) + '.'),
                TextSendMessage('Waiting for next opponent...')
        )
Json:
"armor": [
{
    "name":"Cardboard armor 10 DEF" ,
    "stats":"10" },
{
    "name":"Plastic armor 20 DEF" ,
    "stats":"20" },
{
    "name":"Rubber armor 30 DEF" ,
    "stats":"30" },
{
    "name":"Metal armor 40 DEF" ,
    "stats":"40" },
{
    "name":"Indestructable armor 50 DEF" ,
    "stats":"50" }
],

1 个答案:

答案 0 :(得分:0)

几乎尝试了所有方法之后。解决方案是:

if text == 'FIGHT':
    with open('items.json', 'r') as f:
        data = json.load(f)
        armor2 = random.choice(data['armor'])
        weapon2 = random.choice(data['weapon'])
        magic2 = random.choice(data['magic'])
        calc = add(armor2['stats'], weapon2['stats'], magic2['stats'])
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage('Armor = ' + (armor2['name'])),
                TextSendMessage('Weapon = ' + (weapon2['name'])),
                TextSendMessage('Magic = ' + (magic2['name'])),                 
                TextSendMessage('Total = ' + str(calc) + '.')
            ]
        )

感谢大家,特别感谢我的朋友Sae帮助了我。 :)