如何使用python创建条件JSON?

时间:2018-11-12 10:13:58

标签: python json

您如何在循环中构造一个json,我只需要添加条件数据即可,例如:

        {
         "Country" : [
           {
             "america": {
               "population": "23234234",
               "GDP": "12",
               "measureInVolume": "gallons"
             },
             "argentina": {
               "population": "14234",
               "GDP": "08",
               "measureInVolume": "litres"
             }
           }
          ]
        }

现在,如何根据条件检查该国家/地区是否为python中的“美国”,向国家“美国”添加另一个“犯罪率”字典值?

我正在尝试以以下方式创建它,但无法成功。

            import json

            data = {}
            data['Country'] = []
            counter = 1
            for cnt in range(0, 50):
                data['Country'].append({
                    "<<dynamic Country name from a different function>>": {
                        "population": "23234234",
                        "GDP": "12",
                        "measureInVolume": "gallons"
                    },

                })
                counter = counter + 1
            with open('countryList_gen.json', 'w') as outfile:
                json.dump(data, outfile, indent=4)

请求帮助以解决此问题。因为一旦输入if条件,pycharm上的python编译器就会开始显示错误。

谢谢 沙希德

1 个答案:

答案 0 :(得分:0)

如果我对您的问题理解正确,对我而言,您似乎无需创建国家/地区清单:

如果您是这样开始的:

{
"Country": {
    "test1": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test2": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test3": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test4": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test5": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test6": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    }
}
}

将为您提供以下数据输出:

for cnt in data["Country"]
if cnt == "test2": #you could implement your if clause here
    print("check")
    data['Country'][cnt]["population"] = "update"
    data['Country'][cnt]["GDP"] = "update"
    data['Country'][cnt]["measureInVolume"] = "update"

然后您可以执行以下操作:

{
"Country": {
    "test1": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test2": {
        "population": "update",
        "GDP": "update",
        "measureInVolume": "update"
    },
    "test3": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test4": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test5": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    },
    "test6": {
        "population": "data",
        "GDP": "data",
        "measureInVolume": "gallons"
    }
}

获得以下结果:

{{1}}

}

我希望能有所帮助。