简体   繁体   中英

Why does this python procedure not produce an output after I have parsed the JSON file?

Using this json data I parsed the information correctly but after assigning the parsed data to a variable and running it through the procedure I dont get an output, why?

{"maps":[{"id":"blabla i am spartacus","iscategorical":"0"},{"id":"blabla","iscategorical":"0"}],
"masks":{"id":"valore"},
"om_points":"value",
"parameters":{"id":"valore"}
}

Here is my code:

import json

json_data = open("json_file")
data = json.load(json_data)
json_data.close()

json_list = data ["maps"] [0] ["id"]

def string_search():
    if json_list.count("i") >= 1:
        return True
    return False
import json

json_data = open("data.txt")
data = json.load(json_data)
json_data.close()


json_list = data ["maps"] [0] ["id"]

print json_list   #blabla i am spartacus

def string_search():
    if json_list.count("i") >= 1:
        return True
    return False


result = string_search()
print result     #True

By the way, the name 'json_list' is a horrible name for a string. And in python, string_search() is called a function . And a function should take some inputs, and return a result--it should not read global variables like json_list.

The pro way to write your function would be:

def string_search(a_string): 
    return a_string.count("i") >= 1

And then you would call the function like this:

result = string_search("hi")

Or even:

def string_search(a_string, char):
    return a_string.count(char) >= 1


result = string_search("hello", "l")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM