使用函数输出作为另一个函数的输入

时间:2017-09-26 04:44:15

标签: python python-2.7

我的问题确切地说是我想使用函数输出作为另一个函数的输入,

喜欢:

def first(one,two):
    #some codes gives me info from json files
    api_data = json.loads(api.text)
    return api_data["response"]["info"][one][two];

def second(moreinfo):
    #this code is using first function and gives me the result to do something else on it, beside i want the first function as it is, because i'm using it in the project.
    api_data = json.loads(api.text)
    return api_data[moreinfo]["data"]["name"];

我在文件中使用它来获取第二个函数的结果

second(""+str(first(one,"two"))+"")

我收到了这个错误

return api_data[first(one,"two")]["data"]["name"]
KeyError: 'data'

我认为这个错误是因为第二个函数中的第一个(#,#34;两个")没有, 因为我试图把

return api_data["1"]["data"]["name"] 

它的工作是给我第一个函数的数字1的信息,

谢谢和问候:)

EDITED

json的一些例子

(对于第一个功能)

{
    "response": {
        "info": [
            {
                "id": 1,
                "desc": "desc"
            }
        ]
    }
}

第二个例子(我想在第二个函数中打印)

{
  "1": {
    "data": {
      "name": "Name"
    }
  }
}

2 个答案:

答案 0 :(得分:1)

有两种方法可以根据您的json响应更改代码,也可以根据代码更改json响应。

第一种方法:

api_data = {'1': {'data': {'name': 'name'}}, 'response': {'info': [{"id": 1, "name": "name"}]}}

JSON:

second(""+str(first(0))+"")

功能调用:

api_data = {'1': {'data': {'name': 'name'}}, 'response': {'info': {'one': {'two': 1}}}}

第二种方法:基于您给定的代码,JSON应该是这样的。

second(""+str(first('one', 'two'))+"")

功能调用:

src/gen/java

答案 1 :(得分:0)

当我使用PyQt时的问题,但如果我只是尝试没有PyQt的代码,那么它的工作就好了,问题就不再解决了。

def first(one,two):
    api = requests.get("url")
    api_data = json.loads(api.text)
    return api_data["response"]["info"][one][two]

def second(id):
    api = requests.get("another-url")
    api_data = json.loads(api.text)
    return api_data[id]["data"]["name"]

print(second(str(first("1","id"))))