Формат JSON с питоном - PullRequest
       17

Формат JSON с питоном

0 голосов
/ 20 марта 2019

Я хочу отправить запрос API в этой форме:

         "line_items": [
        {

            "account_id": "1717893000000067010",
            "debit_or_credit": "debit",
            "amount": 400,
            "tags": [
                {
                    "tag_option_id": "1717893000000115007",
                    "tag_id": "1717893000000000333"
                },
                {
                    "tag_option_id": "1717893000000123007",
                    "tag_id": "1717893000000000335"
                },
                {
                    "tag_option_id": "1717893000000126003",
                    "tag_id": "1717893000000000337"
                }
            ]

Указанный выше JSON может содержать сотни (line_items) и каждый (теги) может иметь разное количество словарей.

Что я сделал в Python:

          accounts = []
          tags = []
          for line in payroll.line_ids:

            ######## code missing some correction for tags

            if len(line.x_zoho_jtag) == 0:
               the_tags = {"tag_id": " ", "tag_option_id": " "}
               tags.append(the_tags)


            for tag in line.x_zoho_jtag:
                for option in line.x_zoho_jtag_option:
                    if option.tag_ids == tag.tag_id:
                      the_tags = {"tag_id": tag.tag_id, "tag_option_id": option.option_tag_id}
                      tags.append(the_tags)

              ########

            if line.debit != 0.0:
               credit = {"amount": line.debit,"account_id": line.x_zoho_account_no,"debit_or_credit": "debit", "tags": tags}
               accounts.append(credit)
               print(credit)
            else:
                debit = {"amount": line.credit, "account_id": line.x_zoho_account_no,"debit_or_credit": "credit", "tags": tags}
                accounts.append(debit)
                print(debit)
          print(accounts)

Как вы можете видеть в приведенном выше коде Python, у меня есть 2 списка (учетные записи и теги).Я храню (account_id, debit_or_credit, сумма) в списке (счетов), и он работает нормально.

  if line.debit != 0.0:
           credit = {"amount": line.debit,"account_id": line.x_zoho_account_no,"debit_or_credit": "debit", "tags": tags}
           accounts.append(credit)
           print(credit)
        else:
            debit = {"amount": line.credit, "account_id": line.x_zoho_account_no,"debit_or_credit": "credit", "tags": tags}
            accounts.append(debit)
            print(debit)

Наряду с этим я добавил ключ (теги) и список (теги), как вы можете видеть в приведенной выше строке.

Проблема, с которой я сталкиваюсь, заключается в ключе (теги), где мне нужно передать несколько блоков словарей в список.Так как это сделать?

ожидаемый вывод:

  "line_items": [       
          {
"account_id": "1717893000000067010",
"debit_or_credit": "debit",
"amount": 400,
"tags": [
  {
    "tag_option_id": " ",
    "tag_id": " "
  },
  {
    "tag_option_id": "1717893000000126003",
    "tag_id": "1717893000000000337"
  },
  {
    "tag_option_id": "1717893000000123007",
    "tag_id": "1717893000000000335"
  }


   "line_items": [
       {
"account_id": "1717893000000067036",
"debit_or_credit": "credit",
 "amount": 400,
"tags": [
  {
    "tag_option_id": "1717893000000126003",
    "tag_id": "1717893000000000337"
  }

неправильный вывод:

            {
"account_id": "1717893000000067010",
"debit_or_credit": "debit",
"amount": 400,
"tags": [
  {
    "tag_option_id": " ",
    "tag_id": " "
  },
  {
    "tag_option_id": "1717893000000126003",
    "tag_id": "1717893000000000337"
  },
  {
    "tag_option_id": "1717893000000123007",
    "tag_id": "1717893000000000335"
  }


      {
"account_id": "1717893000000067036",
"debit_or_credit": "credit",
 "amount": 400,
"tags": [
  {
    "tag_option_id": " ",
    "tag_id": " "
  },
  {
    "tag_option_id": "1717893000000126003",
    "tag_id": "1717893000000000337"
  },
  {
    "tag_option_id": "1717893000000123007",
    "tag_id": "1717893000000000335"
  }

Ответы [ 2 ]

1 голос
/ 20 марта 2019

Проблема здесь в том, что когда вы просматриваете теги, вы не различаете те, которые должны идти на credit, и те, которые должны идти на debit.
Что вам нужно сделатьсначала получить строку, а затем получить связанные теги для этой строки.
Я думаю, что ниже должно работать, но с небольшим повторением, поэтому его можно улучшить еще больше.

    accounts = []
    for line in payroll.line_ids:
        if line.debit != 0.0:
            credit = {
                "amount": line.debit,
                "account_id": line.x_zoho_account_no,
                "debit_or_credit": "debit", 
                "tags": []
            }
            if len(line.x_zoho_jtag) == 0:
                credit["tags"].append({"tag_id": " ", "tag_option_id": " "})
            else:
                for tag in line.x_zoho_jtag:
                    for option in line.x_zoho_jtag_option:
                        if option.tag_ids == tag.tag_id:
                          credit["tags"].append({"tag_id": tag.tag_id, 
                                                 "tag_option_id": option.option_tag_id})
            accounts.append(credit)
            print(credit)
        else:
            debit = {
                "amount": line.credit, 
                "account_id": line.x_zoho_account_no,
                "debit_or_credit": "credit", 
                "tags": []
            }
            if len(line.x_zoho_jtag) == 0:
                debit["tags"].append({"tag_id": " ", "tag_option_id": " "})
            else:
                for tag in line.x_zoho_jtag:
                    for option in line.x_zoho_jtag_option:
                        if option.tag_ids == tag.tag_id:
                          debit["tags"].append({"tag_id": tag.tag_id, 
                                                "tag_option_id": option.option_tag_id})

            accounts.append(debit)
            print(debit)

Рефакторинг Далее

Перемещение блока повторяющихся кодов в функцию

accounts = []
for line in payroll.line_ids:
    if line.debit != 0.0:
        credit = create_account("credit", line)
        accounts.append(credit)
        print(credit)
    else:
        debit = create_account("debit", line)
        accounts.append(debit)
        print(debit)


def create_account(account_type, line):
    if account_type == "credit":
        amount = line.debit
        d_or_c = "debit"
    else: 
        amount = line.credit
        d_or_c = "credit"

    account = {
        "amount": amount,
        "account_id": line.x_zoho_account_no,
        "debit_or_credit": d_or_c, 
        "tags": []
    }
    if len(line.x_zoho_jtag) == 0:
        account["tags"].append({"tag_id": " ", "tag_option_id": " "})
    else:
        for tag in line.x_zoho_jtag:
            for option in line.x_zoho_jtag_option:
                if option.tag_ids == tag.tag_id:
                  account["tags"].append({"tag_id": tag.tag_id, 
                                         "tag_option_id": option.option_tag_id})
    return account
0 голосов
/ 20 марта 2019

Полагаю, я вас вижу ... так ... переместите теги = [] в верхний уровень цикла.

...