使用Python循环读取Json文件

2024-04-25 02:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python,我做了一些训练,它可以工作,但不是迭代。 我的json文件如下:

{
 "entities": [
     {
       "id":"int_id1",
       "name":"name1"
       "details":{
          "age":[
              "22"           
           ],
        }
     },
 {
       "id":"int_id2",
       "name":"name2"
       "details":{
          "age":[
              "22"           
           ],
        }
     },
 { 
      "id":"int_id3",
       "name":"name3"
       "details":{
          "age":[
              "22"           
           ],
        }
     }
  ]
}

我试着在上做一些试验,但它只在第一次迭代中起作用。如何修复它以迭代others元素。 我试过:

entities_file = open("from_emplacement")
json_entities_data = json.load(entities_file)
i=0;
for entity in json_entities_data:
    answer = json_entities_data[entity][i]["details"][0]
    if(condition):
      ....
    i+=1;

Tags: 文件nameidjsonagedatadetailsfile
3条回答

试试这个:

entities_file = open("from_emplacement")
json_entities_data = json.load(entities_file)

url_regex = re.compile('(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?')

for entity in json_entities_data["entities"]:
    answer = entity["details"]["answers"]
    for element in answer:
        # case with switch
        if "cases" in element:
            for case in element["cases"]:
                if case["answers"][0].has_key("tips"):
                    tips = case["answers"][0]["tips"]
                    for t in tips:
                        try:
                            for url in url_regex.findall(t):
                                print('://'.join(url[:-1]))
                        except:
                            pass
                        if case["answers"][0].has_key(
                                "texts"):
                            texts = case["answers"][0]["texts"]
                            for text in texts:
                                try:
                                    urls = url_regex.finditer(text)
                                    for url in url_regex.findall(text):
                                        print('://'.join(url[:-1]))
                                except:
                                    pass
        # case without switch
        else:
            for a in element:
                urls = url_regex.finditer(a)
                for url in url_regex.findall(a):
                    print('://'.join(url[:-1]))

注意,这使用regex,所以一定要导入re

{
  "entities": [
     {
          "id": "int_id1",
          "name": "name1",
          "details": {
              "age": [
                  "22"
              ],
              "answers":[
                  {
                 "type":"switch",
                    "cases": [
                         {
                           "case": "fr",
                           "answers": [
                                {
                                  "tips": [
                                        "<https://example.com | some words>"
                                    ],
                                 "texts":[
                                    "some words",
                                    "you can visit <https://faksite.com> and 
                                         <https://otherSite.fr | the second 
                                     one>"
                                 ]
                                }
                           ]
                         },
                      {
                           "case": "us",
                           "answers": [
                                {
                                  "tips": [
                                    "<https://example.com | some words>"
                                    ],
                                  "texts" :[
                                        "some words",
                                        "you can visit <https://faker.com> and 
                                        <https://otherSite.fr | the second 
                                        one>"
                                    ]
                                }
                              ]                         
                        },
                        {
                            "case": "es",
                            "answers": [
                                {
                                    "tips": [],
                                    "texts" :[
                                       "some words",
                                       "you can visit <https://fackesite.com> 
                                        and 
                                             <https://otherSite.fr | the second one>"
                                     ]
                                 }
                             ]
                          }
                       ]
                   }
                 ]
          }
     },
      {
         "id": "int_id2",
          "name": "name2",
          "details": {
              "age": [
                  "22"
                ],
               "answers": [
                     {
                     "texts" :[
                            "some words",
                            "you can visit <https://facker.com> and 
                                 <https://otherSite.fr | the second one>"
                      ]
                     }
                ]
             }
      },      
      {
          "id": "int_id3",
          "name": "name3",
          "details": {
              "age": [
                  "22"
                ],
                 "answers": [
                    {
                     "texts": [
                            "some words",
                            "you can visit <https://fakersite.com> and  <https://otherSite.fr | the second one>"
                      ]         
                    }
                 ]
            }
      }
    ]
}

首先,您需要将JSON格式更正为下面所示的格式,然后再试一次。你知道吗

{
"entities": [{
        "id": "int_id1",
        "name": "name1",
        "details": {
            "age": [
                "22"
            ]
        }
    },
    {
        "id": "int_id2",
        "name": "name2",
        "details": {
            "age": [
                "22"
            ]
        }
    },
    {
        "id": "int_id3",
        "name": "name3",
        "details": {
            "age": [
                "22"
            ]
        }
    }
]
}

相关问题 更多 >