简体   繁体   English

如何从Swift 4 / json字典中的多值键检索单个值?

[英]how can I retrieve individual values from a multi value key in Swift 4/json dictionary?

There are many many examples of retrieving the value of a key, and I can do that. 有许多检索键值的示例,我可以做到这一点。 In this case, the key has multiple values. 在这种情况下,键具有多个值。 The key is "mining", followed by 6 values. 关键是“挖掘”,后跟6个值。 The same key:value is repeated 30 times, with different values for the keys of course. 相同的key:value重复30次,当然,这些key的值也不同。

What I can't seem to solve is how to return the values. 我似乎无法解决的是如何返回值。 Especially the first one, 1532825277682891390, for example, which appears to be a sub-key with key/value pairs related to that. 尤其是第一个,例如1532825277682891390,它似乎是一个具有与此相关的键/值对的子键。

The todo is: ["mining": {
1532825277682891390 =     {
    command = mining;
    siteid = "Platform Mining";
    ts = 1532825270557;
    user1 = 73276;
    value = 1;
};
1532826406100318457 =     {
    command = mining;
    siteid = "Platform Mining";
    ts = 1532826375712;
    user1 = 73276;
    value = 1;
};
1532827074955562013 =     {
    command = mining;
    siteid = "Platform Mining";
    ts = 1532827066645;
    user1 = 73276;
    value = 1;
};
153282775791322835 =     {
    command = mining;
    siteid = "Platform Mining";
    ts = 1532827753205;
    user1 = 73276;
    value = 1;
};

....
....
....
}

I can show the key:value for the "mining" key. 我可以显示“挖掘”键的key:value。 There are only two keys in the dictionary, 'mining' and 'success' - I'm not worried about 'success', it usually returns '1'. 字典中只有两个键:“采矿”和“成功”-我并不担心“成功”,它通常返回“ 1”。

This is basically the code with a few examples and trial outputs, as I try out different things from other posts. 这基本上是带有一些示例和试用输出的代码,因为我尝试了与其他文章不同的东西。 I just can't get my head around this bit. 我只是无法理解这一点。 Do I need to put the dictionary into an array, and how do I do that, or can I just put each value into a var, so I can print them to a UITabDisplay? 我是否需要将字典放入数组中,以及如何将其放入一个var中,以便可以将它们打印到UITabDisplay?

    func makeGetCall() {
    // Set up the URL request
    let todoEndpoint: String = "https://api.jsecoin.com/v1.7/mining/auth/"

    let apiKey = "xxxxxxxxxxxxxxxxxxxxxxx"


    guard let url = URL(string: todoEndpoint) else {
        print("Error: cannot create URL")
        return
    }
    var urlRequest = URLRequest(url: url)

    urlRequest.setValue(apiKey, forHTTPHeaderField: "Authorization")
    urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    // set up the session
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    // make the request
    let task = session.dataTask(with: urlRequest) {
        (data, response, error) in
        // check for any errors
        guard error == nil else {
            print("error calling GET on /todos/1")
            print(error!)
            return
        }


        // make sure we got data
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }
        print("Got data: \(responseData)")
        // parse the result as JSON, since that's what the API provides
        do {
            guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
                as? [String: Any] else {
                    print("error trying to convert data to JSON")
                    return
            }
            // now we have the todo
            // let's just print it to prove we can access it
           print("The todo is: " + todo.description)

           // from this point on I"m experimenting ....

            let dict = todo.description
            print("The dict is: " + dict)

            let keys = Array(todo.keys)
            // prints ["mining", "success"]
            print(keys)
            /////////////////////////////////
            if let alb = todo["mining"] {
                // prints all the values for 'mining'.
               //  {
               //   1532825277682891390 =     {
               //   command = mining;
               //   siteid = "Platform Mining";
               //   ts = 1532825270557;
              //    user1 = 73276;
              //    value = 1;
             //    };
             // ........ 30 entires
                print(alb)
            }
            //======================
            let index1 = todo.index(forKey: "mining")
            let myMining = (todo[index1!].value)

            // again prints all the mining values. Mining: {
            // 1532825277682891390 =     {
            // command = mining;
            // siteid = "Platform Mining";
            // ts = 1532825270557;
            // user1 = 73276;
            // value = 1;
            // };

            print("Mining: \(myMining)")

            //============ 

You can do it in a similar way you have written for taking the keys of todo dictionary. 您可以采用与获取todo字典的键类似的方式进行操作。

if let mining = todo["mining"] as? [String: Any] {
   let miningKeys = Array(mining.keys)
   // It will be like [1532825277682891390, 1532826406100318457]
}

Use the miningKeys for accessing the values from that mining dictionary, like: 使用miningKeys来访问该挖掘字典中的值,例如:

mining[miningKeys.first!]
// It will return
// {
//   command = mining;
//   siteid = "Platform Mining";
//   ts = 1532825270557;
//   user1 = 73276;
//   value = 1;
// }

The value for key mining is a dictionary. 密钥mining的值是字典。 Conditional downcast alb to the expected type and enumerate the dictionary 有条件地将alb转换为期望的类型并枚举字典

if let alb = todo["mining"] as? [String:Any] {
    for (key, value) in alb {
        print(key, value)
    }
}

If you want to print each key-value pair of the inner dictionary separately you could use 如果要分别打印内部字典的每个键值对,则可以使用

if let alb = todo["mining"] as? [String:Any] {
    for (key, mining) in alb {
        print(key)
        if let item = mining as? [String:Any] {
           for (key, value) in item {
               print(key, value)
           }
        }
    }
}

Consider that the key s in the for loop are not guaranteed to be in the same order as in the JSON. 考虑到for循环中的key s不能保证与JSON中的键相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM