简体   繁体   English

如何在MongoDB对象的Json内的Python中打印值

[英]How to print a value in Python that is inside a Json in MongoDB object

I have this Json, and I need a value from a rate. 我有这个杰森(Json),我需要一个比率值。

 "_id" : ObjectId("5addb57d0043582d48ba898a"),
"success" : true,
"timestamp" : 1524477784,
"base" : "EUR",
"date" : "2018-04-23",
"rates" : {
    "AED" : 4.492662,
    "AFN" : 85.576329,
    "ALL" : 128.39508,
    "AMD" : 586.837094,
    "ANG" : 2.177608,
    "AOA" : 267.092358,
    "ARS" : 24.678283,
    "AUD" : 1.602032,
    "AWG" : 2.177639,
    "AZN" : 2.079155,
    "BAM" : 1.958775,
    "BBD" : 2.446786,
    "BDT" : 101.517146,
    "BGN" : 1.943843,
    "BHD" : 0.460968,
    "NOK" : 9.626194,
 }

And this is my Python code 这是我的Python代码

import pymongo

uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']
collection2 = database['countries']
p = str(input('Insert the country: ')).capitalize()

if p=='Norway':
currency = collection.find_one({'NOK'})
print(currency)

I want to print the value inside de NOK, how can I do it? 我想在de NOK中打印值,我该怎么做? Thanks in advance. 提前致谢。

I think you can call it by : 我认为您可以通过以下方式致电:

currency = collection.find_one({"NOK"})
print(currency['rates']['NOK'])

What you're trying to do is fetch a value in a dictionary which is integrated inside of another dictionary. 您想要做的是从集成在另一个字典中的字典中获取一个值。 JSON returns are dictionaries. JSON返回是字典。

I imagine that the collection variable contains the JSON return 我想像集合变量包含JSON返回

One way of fetching this data is by calling the dictionary and telling it what key you want the dictionary to return, as the "NOK" key is in the "rates" key we will be calling the rates key first, then when the dictionary has returned the dictionary that contains the "NOK" key we will then pass the "NOK" key to that returned dictionary, so the code looks like this: 获取此数据的一种方法是调用字典,并告诉它您希望字典返回什么键,因为“ NOK”键位于“ rates”键中,因此我们将首先调用rates键,然后在字典具有返回包含“ NOK”键的字典,然后我们将“ NOK”键传递给该返回的字典,因此代码如下所示:

    currency = collection["rates"]["NOK"]

Another way of doing this is using the for loop, it is a lot longer but may help you understand. 这样做的另一种方法是使用for循环,它虽然长很多,但可以帮助您理解。

    for key in collection:
        if key == "rates":
            for keyRates in JSON[key]:
                if keyRates == "NOK":
                     currency = JSON[key][keyRates]

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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