【问题标题】:Import a json file, but only use the information one line at a time导入一个 json 文件,但一次只使用一行信息
【发布时间】:2020-05-31 20:36:41
【问题描述】:

我正在写作,因为我认为我要问的内容需要多个不同的功能才能实现,我不确定应该如何构建。

import json

filename = rs.OpenFileName("Open JSON File", filter)

#Read JSON data into the results variable
if filename:
with open(filename, 'r') as f:
    results = json.load(f)

将数据导入results变量,并说这是json文件中的数据。

{"votes": {"funny": 2, "useful": 5, "cool": 1}, "user_id": "harveydennis", "name": "Jasmine Graham", "url": "http://example.org/user_details?userid=harveydennis", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 2, "cool": 4}, "user_id": "njohnson", "name": "Zachary Ballard", "url": "https://www.example.com/user_details?userid=njohnson", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 0, "cool": 4}, "user_id": "david06", "name": "Jonathan George", "url": "https://example.com/user_details?userid=david06", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 6, "useful": 5, "cool": 0}, "user_id": "santiagoerika", "name": "Amanda Taylor", "url": "https://www.example.com/user_details?userid=santiagoerika", "average_stars": 3.5, "review_count": 12, "type": "user"}
{"votes": {"funny": 1, "useful": 8, "cool": 2}, "user_id": "rodriguezdennis", "name": "Jennifer Roach", "url": "http://www.example.com/user_details?userid=rodriguezdennis", "average_stars": 3.5, "review_count": 12, "type": "user"}

现在我想要一个 if then 语句使用它并分配给一个单独的变量,但它是逐行进行的。

如果 "funny" >= 5 那么 "user_id" = variableName

做{

然后我将在下面包含一个 do 命令,该命令将使用该变量,Everything 将使用下一个条目(下一个投票行)重新启动,直到没有任何条目为止。

这甚至可能吗?如果是这样,那会怎样?

【问题讨论】:

  • 那是JSONLines
  • 从技术上讲,您的文件不是 json,但您可以逐行读取文件,并为每一行读取“results = json.loads(line)”。

标签: python json sorting if-statement variables


【解决方案1】:

希望我能正确理解您的问题,您可以遍历文件中的行并为每一行生成一个 json 对象

with open("file.txt", "r") as file:
    for line in file:
        current_json = json.loads(line)
        your_awesome_function(current_json["votes"]["funny"])

【讨论】:

  • 然后我就可以根据 if then 语句来分配变量了吗?
  • 你可以像if current_json["votes"]["funny"] >= 5: my_variable = current_json["user_id"]这样访问数据。请注意,您需要在 for 循环中使用它,否则您的值将在下一次循环迭代中被覆盖。
猜你喜欢
  • 1970-01-01
  • 2018-02-16
  • 2019-08-29
  • 1970-01-01
  • 2013-09-04
  • 2012-11-12
  • 2018-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多