【问题标题】:Return objects separately in json在 json 中分别返回对象
【发布时间】:2017-07-27 02:04:29
【问题描述】:
        "allytips": [
            "Jax can Leap Strike to friendly units, including wards. You can use them to plan your escape.",
            "Jax benefits greatly from items that have both Ability Power and Attack Damage such as Guinsoo's Rageblade and Hextech Gunblade."
        ],

我正在尝试将 allytips 中的上述数据作为单独的对象返回,以便我能够以更吸引人的方式进行格式化/风格化,例如在每个字符串末尾的 \n 我尝试了 for 语句,因为我认为它会使它更易于访问,但事实并非如此,它只打印一个通常是最后一个的对象。我可以做 if 语句将它们分配给一个变量,然后用它制作一个干净的打印语句,但我不确定我会怎么做 .format() 因为如果它不存在它会给我一个错误,我会如果我这样做 \n{4} \n{5} 会有很多空行并且它们不存在

try:
            for tips in self.j['data'][champEntry]['allytips']:
                self.allyTips0 = tips
            print(tips)
            allyRaw = self.j['data'][champEntry]['allytips']
            print(allyRaw)

这就是它返回的内容,第一行我提到它一次只打印一个对象而不是最后一个对象

Remember that nearby enemies can see which wall you're in.
["Look at the line-up of both your team and the enemy's team when picking your form.", "Remember that nearby enemies can
see which wall you're in."]

我试图让它看起来像这样

Look at the line-up of both your team and the enemy's team when picking your form.
Remember that nearby enemies can see which wall you're in.

【问题讨论】:

    标签: json python-3.x parsing object


    【解决方案1】:

    尝试添加这样的循环

    for i in range(0,len(self.j['data'][champEntry]['allytips'])):
            print self.j['data'][champEntry]['allytips'][i],"\n"
    

    【讨论】:

      【解决方案2】:

      尝试使用 split() 方法,该方法将通过分隔符进行拆分,创建一个数组。然后按索引选择。

      allyRaw1 = self.j['data'][champEntry]['allytips'].split(',')[0]
      
      allyRaw2 = self.j['data'][champEntry]['allytips'].split(',')[1]
      

      【讨论】:

      • 拆分没有意义我可以做 allyRaw1 = self.j['data'][cham​​pEntry]['allytips'][0] 但我不想创建一堆if 语句来分配变量,如果它存在,因为可能有超过 8 或 10 个字符串,然后必须执行类似 print(\n{0} \n {1} \n{2}).format(allyRaw, allyRaw1 , allyRaw2) 如果 allyRaw2 不存在会变得一团糟
      猜你喜欢
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      相关资源
      最近更新 更多