简体   繁体   English

Python字典到JSON文件转换问题

[英]Python Dictionary to JSON file conversion problem

so i've been working on a project that scrapes a finance site and saves the top 5 fastest changing stocks in a json file for later usage.所以我一直在研究一个项目,该项目抓取金融网站并将前 5 名变化最快的股票保存在 json 文件中以供以后使用。 My Problem is it doesn't format it right.我的问题是它的格式不正确。

Function that converts it to JSON:将其转换为 JSON 的函数:

def writeToJSON(num, short, name, price, change):
stocks = {}
numStock = {
    "Short" : short,
    "Name" : name,
    "Price" : price,
    "Change" : change
    }


stocks.update({str(num) : numStock,})
with open(".\\sstocksim\\stocks.json", "a") as f:
    json.dump(stocks, f, indent=3)
    f.close()

JSON Output: JSON 输出:

 {
   "1": {
      "Short": "AXSM",
      "Name": "Axsome Therapeutics, Inc.",
      "Price": "81.64",
      "Change": "+34.85"
   }
}{
   "2": {
      "Short": "TSLA",
      "Name": "Tesla, Inc.",
      "Price": "381.44",
      "Change": "+23.05"
   }
}{
   "3": {
      "Short": "CGX.TO",
      "Name": "Cineplex Inc.",
      "Price": "33.83",
      "Change": "+9.82"
   }
}{
   "4": {
      "Short": "MIRM",
      "Name": "Mirum Pharmaceuticals, Inc.",
      "Price": "17.17",
      "Change": "+8.98"
   }
}{
   "5": {
      "Short": "AMGN",
      "Name": "Amgen Inc.",
      "Price": "244.51",
      "Change": "+7.77"
   }
}

For some reason it puts an EOF after every entry and I can't figure out how to stop it from doing that.出于某种原因,它在每次输入后都会放置一个 EOF,我不知道如何阻止它这样做。 Thanks in advance!!提前致谢!!

EDIT:编辑:

You probably know how its supposed to look but just in case, thats the output i want:您可能知道它应该是什么样子,但以防万一,这就是我想要的输出:

{
   "1": {
      "Short": "AXSM",
      "Name": "Axsome Therapeutics, Inc.",
      "Price": "81.64",
      "Change": "+34.85"
   },

   "2": {
      "Short": "TSLA",
      "Name": "Tesla, Inc.",
      "Price": "381.44",
      "Change": "+23.05"
   },

   "3": {
      "Short": "CGX.TO",
      "Name": "Cineplex Inc.",
      "Price": "33.83",
      "Change": "+9.82"
   },

   "4": {
      "Short": "MIRM",
      "Name": "Mirum Pharmaceuticals, Inc.",
      "Price": "17.17",
      "Change": "+8.98"
   },

   "5": {
      "Short": "AMGN",
      "Name": "Amgen Inc.",
      "Price": "244.51",
      "Change": "+7.77"
   }
}

You are writing to the file once per numStock ;您每个numStock写入一次文件; that is, when you write the file, stocks contains a single item, which is the current numStock .也就是说,当您写入文件时, stocks包含一个项目,即当前的numStock

Instead, create a stocks dictionary that contains all of your numStock items, then write that to file.相反,创建一个包含所有numStock项目的stocks字典,然后将其写入文件。

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

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