Цикл в Python для чтения файла Json - PullRequest
0 голосов
/ 27 января 2019

используя 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"           
           ],
        }
     }
  ]
}

Я пытаюсь использовать черты, но это работает только на первой итерации. Как я могу исправить это, чтобы повторить элемент других. Я попробовал:

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;

Ответы [ 3 ]

0 голосов
/ 27 января 2019

Попробуйте это:

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]))

Обратите внимание, что здесь используется регулярное выражение, поэтому обязательно импортируйте re

0 голосов
/ 28 января 2019
{
  "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>"
                      ]         
                    }
                 ]
            }
      }
    ]
}
0 голосов
/ 27 января 2019

Прежде всего вам необходимо исправить свой формат 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"
            ]
        }
    }
]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...