group json according to data

0

Hi, I hope you are well, I have a problem which I can not solve. having the following json I want to group by ** state * to then create a new example:

  [{
    "area": "YUMBO",
    "state": "NOT"
  },
  {
    "area": "ZARZAL",
    "state": "VCAU"
  },
  {
    "area": "PUERTO CARRENO",
    "state": "VIC"
  },
  {
    "area": "SANTA ROSALIA",
    "state": "VIC"
  }
]

which I wish so:

[{"NOT":{"YUMBO"},
 "VCAU":{"ZARZAL"},
 "VIC":{"PUERTO CARRENO","SANTA ROSALIA"}
}]

[{ "NOT": {"YUMBO"}, "VCAU": {"ZARZAL"}, "VIC": {"PUERTO CARRENO", "SANTA ROSALIA"} }]

What I have so far is this where I create an array where I store the state without repeating but I would not know how to add the area part as appropriate, thank you very much

b=[]
c=[]
for (i = 0; i < a.length; i++) {
  if(b.includes(a[i].state)){
  }else{
    b.push(a[i].state);
  }
}
    
asked by NEFEGAGO 01.03.2018 в 03:48
source

1 answer

1

Because of what I was looking at the JSON that you want as a result it would not be valid. Deputy evidence

The following code I made provides a valid JSON with what you want

import json

lista=[{
    "area": "YUMBO",
    "state": "NOT"
  },
  {
    "area": "ZARZAL",
    "state": "VCAU"
  },
  {
    "area": "PUERTO CARRENO",
    "state": "VIC"
  },
  {
    "area": "SANTA ROSALIA",
    "state": "VIC"
  }
]
resultado=dict()
for index in range(len(lista)):
     if resultado.get(lista[index]["state"],None)==None:
                    resultado[lista[index]["state"]]=[]
     resultado[lista[index]["state"]].append(lista[index]["area"])
jsonarray = json.dumps(resultado)
print(jsonarray)

The output in this case would be:

{"NOT": ["YUMBO"], "VIC": ["PUERTO CARRENO", "SANTA ROSALIA"], "VCAU": ["ZARZAL"]}

The validation in this case is OK

Greetings and I hope it serves you.

    
answered by 01.03.2018 / 05:50
source