Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

How to parse JSON data and eliminate duplicates in Swift?

I have a very large JSON file that I have downloaded from the web, and I need to parse this in Swift. The JSON construction is an array of dictionaries. Each dictionary object contains a key of "phone" (referring to the phone number), and whose value is the actual phone number in the form of a string.

What I would like to do, is iterate through the entire list of dictionary objects in the array, and ensure that there are no dictionary objects that have the same value for the key, "phone". If a duplicate is found, I would like to eliminate it from the list, and print it out to the console.

Here is the relevant code that I have:

            guard let json = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
                print("error")
                return
            }

            for dict in json! {
                //This is where I would do the check

            }

How would I accomplish this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do as

var ph = [String]()
var newjson = [[String:String]]()

    for dict in json {
        if ph.contains(dict["Phone"]!) {

            print("duplicate phone (dict["Phone"]!)")

        } else {

        ph.append(dict["Phone"]!)
        newjson.append(dict)

        }
    }
    print(newjson)

Hare newjson is the new array of dictionary that do not have duplicate phone


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...