Home > Enterprise >  How toconvert multiple one-dimensional json to one multidimensional?
How toconvert multiple one-dimensional json to one multidimensional?

Time:07-10

Hello help me please friends! I have:

[
    {
        "id": 1,
        "name": "Zach But",
        "article": "Article_1"
    },
    {
        "id": 2,
        "name": "Zach But",
        "article": "Article_2"
    },
    {
        "id": 3,
        "name": "Ann Spring",
        "article": "Article_3"
    },
    {
        "id": 4,
        "name": "Ann Spring",
        "articles": "Article_4"
    }
  ]

Need result:

[
    {
        "id": 1,
        "name": "Zach But",
        "article": [
                    "Article_1",
                    "Article_2"
                   ]
    },
    {
        "id": 2,
        "name": "Ann Spring",
        "article": [
                    "Article_3",
                    "Article_4"
                   ]
    }
  ]

That is, I have duplicate data on authors who have different articles, and I need to add these articles to each of the authors so that the authors do not repeat themselves. Please tell me how to do it right.

f = open('authors_test.json')
data = json.load(f)
for i in range(0, len(data)):

    if data[i]['name'] == data[i-1]['name']:
    # dont know

I can load json from a file and compare objects by author name, but I don’t know how to further implement what I need so that I end up with one object with each author, which has an array of articles

CodePudding user response:

You can write a python code where if the JSON values name are equal, append the article value to an articles array

Code:

newarr = []
for i in range(1, len(arr)):
    if arr[i].name == arr[i-1].name:
        newarr[i].append(arr[i].article)
        newarr[i].append(arr[i].name)
        newarr[i].append(arr[i].id)

CodePudding user response:

Try:

data = [
    {"id": 1, "name": "Zach But", "article": "Article_1"},
    {"id": 2, "name": "Zach But", "article": "Article_2"},
    {"id": 3, "name": "Ann Spring", "article": "Article_3"},
    {"id": 4, "name": "Ann Spring", "articles": "Article_4"},
]

out = {}
for d in data:
    out.setdefault(d["name"], []).append(d.get("article", d.get("articles")))

out = [
    {"id": i, "name": name, "article": out[name]}
    for i, name in enumerate(out, 1)
]
print(out)

Prints:

[
    {"id": 1, "name": "Zach But", "article": ["Article_1", "Article_2"]},
    {"id": 2, "name": "Ann Spring", "article": ["Article_3", "Article_4"]},
]
  • Related