Z
Z
zensimilia2020-05-15 12:59:42
Python
zensimilia, 2020-05-15 12:59:42

How to change the json structure of the response on the client?

There is a service that returns json via API in the following format:

response

{
  "result": [
    {
      "Columns": [
        {
          "Title": "id"
        },
        {
          "Title": "Name"
        },
        {
          "Title": "mapScale"
        },
        {
          "Title": "code"
        }
      ],
      "Data": [
        [
          "4",
          "Краснодар",
          "11",
          "krasnodar"
        ],
        [
          "7",
          "Анапа",
          "14",
          "anapa"
        ],
        [
          "14",
          "Геленджик",
          "14",
          "gelendzhik"
        ],
        [
          "15",
          "Новороссийск",
          "10",
          "novorossiysk"
        ],
        [
          "16",
          "Ростов-на-Дону",
          "12",
          "rostov"
        ],
        [
          "17",
          "Сочи",
          "15",
          "sochi"
        ],
        [
          "24",
          "Афипский",
          "10",
          ""
        ],
        [
          "67",
          "Майкоп",
          "10",
          "maykop"
        ]
      ],
      "totalRow": 255
    }
  ]
}


It is not very convenient to work with such a structure, when it would be ideal to receive:

{
  "data": [
    {
      "id" : "187",
      "Name": "Москва",
      "mapScale": "4",
      "code": "moscow"
    },
    {
      ...
    },
    "totalRow": 255
  ]
}


Unfortunately, I do not have the opportunity to change the format on the service itself that gives the answer. The data may be large.

Tell me what is the best way to process this json in order to bring it back to normal, or maybe there is some library (python / node) that allows you to do this easily.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Alexandrov, 2020-05-15
@zensimilia

def f_json(json):
    res = json["result"][0]
    cols = [list(col.values())[0] for col in res["Columns"]]
    return {"data": [dict(zip(cols, row)) for row in res["Data"]]}

Well, that's how it's done

A
afishr, 2020-05-15
@afishr

As noted in the comments, this is done simply by a loop. I posted an example here , maybe it will help you figure it out.

D
Dmitry, 2020-05-15
@LazyTalent

If there is a lot of data, then I would use pandas

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question