Skip to content Skip to sidebar Skip to footer

Python-select Unique Key Values From Json Object

I have a json response: { 'data': [ { 'id': '1', 'name': 'Tom', 'age': '24', }, { 'id': '2', 'name': 'Nick', 'age': '45', }, { 'id': '3

Solution 1:

Here's how you should fix your code: Simply keep your registry of names and then add a algorithm for keeping the rest of the information. For me, I created another array for storing the whole data object that have unique names, called returnValue. And whenever there is a unique name, it pushes the entire data object onto returnValue. Then, it prints it out (or returns it, if you turn it into a function).

returnValue = []
size=len(data["data"])
uniqueNames = []
for i in range(0,size,1):  
    if(data["data"][i]["name"] not in uniqueNames):
         uniqueNames.append(data["data"][i]["name"]) 
         returnValue.append(data["data"][i])
print returnValue

Because of author's question:

returnValue = []
badValues = []
size=len(data["data"])
uniqueNames = []
for i in range(0,size,1):  
    if(data["data"][i]["name"] not in uniqueNames):
         uniqueNames.append(data["data"][i]["name"]) 
         returnValue.append(data["data"][i])
    else:
         badValues.append(data["data"][i])
print"Good ones: "print returnValue
print"Bad ones: "print badValues

Solution 2:

Here you go,

import json
jsonFile = open('aa.json', 'r')
data = json.load(jsonFile)

size=len(data["data"])
print size
values = [];
uniqueNames = [];
for i in data["data"]:
    if(i["name"] not in uniqueNames):
         uniqueNames.append(i["name"]);
         values.append(i)
jsonFile.close()

Post a Comment for "Python-select Unique Key Values From Json Object"