Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...