首页 文章

将已删除的数据附加到JSON文件

提问于
浏览 41
1

我试图从报废的数据中制作一个json文件 . 但是根据我的函数converToJson(),它会覆盖前一个条目而不会附加 . 是因为我不是在迭代它吗?例如:下面的Json文件将每次使用新数据覆盖第一个条目而不是附加到它 .

[{"Volume": "Volume:\n6,061,086", "Price": "$ 41.88", "Name": "Suncor Energy Inc."}]

def getStockDetails(url, browser):

        print(url)
        browser.get(url)

        quote_wrapper = browser.find_element_by_css_selector('div.quote-wrapper')
        quote_name = quote_wrapper.find_element_by_class_name(
            "quote-name").find_element_by_tag_name('h2').text
        quote_price = quote_wrapper.find_element_by_class_name("quote-price").text
        quote_volume = quote_wrapper.find_element_by_class_name(
            "quote-volume").text

        print("\n")
        print("Quote Name: " + quote_name)
        print("Quote Price: " + quote_price)
        print("Quote Volume: " + quote_volume)
        print("\n")

        convertToJson(quote_name,quote_price,quote_volume)


 def convertToJson(quote_name,quote_price,quote_volume):
        quotesArr = []
        quoteObject = {
            "Name": quote_name,
            "Price": quote_price,
            "Volume": quote_volume
        }
        quotesArr.append(quoteObject)

        with open('trendingQuoteData.json', 'w') as outfile:
            json.dump(quotesArr, outfile)

2 回答

  • 1
    import json
    
    a = json.loads(jsonStringA)
    b = json.loads(jsonStringB)
    c = dict(a.items() + b.items())
    # or c =  dict(a, **b)
    
  • 0

    你需要使变量 quotesArr 全局,把它放在函数外面,并在完成后编写你的json .

    quotesArr = []
    def convertToJson(quote_name,quote_price,quote_volume):
        quoteObject = {
            "Name": quote_name,
            "Price": quote_price,
            "Volume": quote_volume
        }
        quotesArr.append(quoteObject)
    
    def trendingBot(url, browser):
        browser.get(url)
        trending = getTrendingQuotes(browser)
        for trend in trending:
            getStockDetails(trend, browser)
        # requests finished, write json to file
        with open('trendingQuoteData.json', 'w') as outfile:
            json.dump(quotesArr, outfile)
    

相关问题