如何将这种JSON数据解析为数组?

时间:2018-12-25 07:51:15

标签: arrays json parsing

重新修复解析代码,并获得以下JSON。如何继续创建2个单独的数组:一个用于prefcode,一个用于prefName?

JSON:

  

[         {           “ prefCode”:1           “ prefName”:“北海道”         },         {           “ prefCode”:2           “ prefName”:“青森県”         },         {           “ prefCode”:3,           “ prefName”:“岩手県”         },         {           “ prefCode”:4,           “ prefName”:“宫城県”         },         {           “ prefCode”:5           “ prefName”:“秋田県”         },         {           “ prefCode”:6           “ prefName”:“山形県”         },         {           “ prefCode”:7           “ prefName”:“福岛県”         },         {           “ prefCode”:8           “ prefName”:“茨城県”         },         {           “ prefCode”:9           “ prefName”:“栃木県”         },         {           “ prefCode”:10,           “ prefName”:“群马県”         },         {           “ prefCode”:11           “ prefName”:“埼玉県”         },         {           “ prefCode”:12           “ prefName”:“千叶県”         },         {           “ prefCode”:13           “ prefName”:“东京都”         },         {           “ prefCode”:14           “ prefName”:“神奈川県”         },         {           “ prefCode”:15           “ prefName”:“新泻県”         },         {           “ prefCode”:16           “ prefName”:“富山県”         },         {           “ prefCode”:17           “ prefName”:“石川県”         },         {           “ prefCode”:18,           “ prefName”:“福井県”         },         {           “ prefCode”:19,           “ prefName”:“山梨県”         },         {           “ prefCode”:20,           “ prefName”:“长野県”         },         {           “ prefCode”:21,           “ prefName”:“岐阜県”         },         {           “ prefCode”:22,           “ prefName”:“静冈県”         },         {           “ prefCode”:23,           “ prefName”:“爱知県”         },         {           “ prefCode”:24,           “ prefName”:“三重県”         },         {           “ prefCode”:25,           “ prefName”:“滋贺県”         },         {           “ prefCode”:26,           “ prefName”:“京都府”         },         {           “ prefCode”:27,           “ prefName”:“大阪府”         },         {           “ prefCode”:28,           “ prefName”:“兵库県”         },         {           “ prefCode”:29,           “ prefName”:“奈良県”         },         {           “ prefCode”:30,           “ prefName”:“和歌山県”         },         {           “ prefCode”:31,           “ prefName”:“鸟取県”         },         {           “ prefCode”:32,           “ prefName”:“岛根県”         },         {           “ prefCode”:33,           “ prefName”:“冈山県”         },         {           “ prefCode”:34,           “ prefName”:“広島県”         },         {           “ prefCode”:35,           “ prefName”:“山口県”         },         {           “ prefCode”:36,           “ prefName”:“徳岛県”         },         {           “ prefCode”:37,           “ prefName”:“香川県”         },         {           “ prefCode”:38,           “ prefName”:“爱媛県”         },         {           “ prefCode”:39,           “ prefName”:“高知県”         },         {           “ prefCode”:40,           “ prefName”:“福冈県”         },         {           “ prefCode”:41,           “ prefName”:“佐贺県”         },         {           “ prefCode”:42           “ prefName”:“长崎県”         },         {           “ prefCode”:43           “ prefName”:“熊本県”         },         {           “ prefCode”:44           “ prefName”:“大分県”         },         {           “ prefCode”:45,           “ prefName”:“宫崎県”         },         {           “ prefCode”:46,           “ prefName”:“鹿児岛県”         },         {           “ prefCode”:47,           “ prefName”:“冲縄県”         }       ]

ViewController代码:

import UIKit
    import SwiftyJSON
    import Alamofire
    import Foundation

    struct Citys: Decodable {
        let prefCode: Int
        let cityName: String
        let cityCode: Int
        let bigCityFlag: Int

    }


    class ViewController: UIViewController {

        @IBOutlet weak var City: UILabel!


        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib


            if let BASEURL = URL(string: "https://opendata.resas-portal.go.jp/api/v1/prefectures?") {
                var urlRequest = URLRequest(url: BASEURL)
                urlRequest.httpMethod = HTTPMethod.get.rawValue

                var headers: HTTPHeaders
                if let existingHeaders = urlRequest.allHTTPHeaderFields {
                    headers = existingHeaders
                } else {
                    headers = HTTPHeaders()
                }
                headers["X-API-KEY"] = "4GMF0uUh7T9UHFvcp8xq6r4WnGnBA6arqJpuoPIS"
                //headers["Content-Type"] = "application/json;charset=UTF-8"
                headers["Content-Type"] = "application/json"
                headers["charset"] = "utf-8"
                urlRequest.allHTTPHeaderFields = headers

                let request = Alamofire.request(urlRequest)
                    .responseJSON { response in
                        //debugPrint(response)
                        guard let object = response.result.value else {
                            print("Error")
                            return
                        }

                        //print(response)
                        let propertyJSON : JSON = JSON(response.result.value!)
                        self.updateName(json: propertyJSON)

                }

            }
        }

        //MARK: - JSON Parsing
        /***************************************************************/

        func updateName(json : JSON) {

            for result in json {
                print(result.1)
            }

2 个答案:

答案 0 :(得分:0)

这不是有效的Json Data,我不建议使用这种方法。但是,如果需要的话,可以使用正则表达式和字符串替换来解析它,如下所示。考虑到$ DATA变量包含您在上面发布的内容。

// Replace the following characters: ( ) = ; with these: [ ] : ,
// and escape backslashes, \ becomes \\ (also must be escaped for the str_replace call)
$DATA = str_replace(['(',')', '=', ';', '\\'], ['[',']',':', ',', '\\\\'], $DATA);

// Remove SUCCESS: from the start
$DATA = trim($DATA, 'SUCCESS:');

// Wrap keys with quotes ""
$DATA = preg_replace('/([a-zA-Z0-9]+)\s\:/', '"$1":', $DATA);

// Trim zeros from integer values
$DATA = preg_replace('/:\s[0]+[1-9]/', ': ', $DATA);

// Remove comma from last item in array
$DATA = preg_replace('/,([\r|\n|\s]+)([\[|\}|\)])/', '$1$2', $DATA);

// Decode Json
$JSON = json_decode($DATA);

// Voila!
print_r($JSON);

答案 1 :(得分:0)

首先,本尼(Benny),您以JSON数据形式提供的数据作为JSON数据无效。有很多错误。我在下面列出了它们:

  • 在每个键值对中,键和值应该用 :隔开,而不是用=隔开。例如:message = "<null>" ==> message: "<null>"
  • 成功的键/值对应该用逗号而不是;隔开。例如:bigCityFlag = 2; cityCode = 01100; ==> bigCityFlag: 2, cityCode: 01100,

  • 我想,result应该是对象数组。如果我是对的,则应将其包含在[ ]而不是( )内,这将使它成为:result: ({ ==> result: [{

Emmanuel has suggested a good way to make these changes.假设您已使用此方法或其他方法将其纠正为有效的JSON数据,则可以使用以下方法将其中的result部分放入相应的数组中。

var SUCCESS = {
  message: "<null>",
  result: [{
    bigCityFlag: 2,
    cityCode: 01100,
    cityName: "\U672d\U5e4c\U5e02",
    prefCode: 1
  }, {
    bigCityFlag: 1,
    cityCode: 01101,
    cityName: "\U672d\U5e4c\U5e02\U4e2d\U592e\U533a",
    prefCode: 1
  }, {
    bigCityFlag: 1,
    cityCode: 01102,
    cityName: "\U672d\U5e4c\U5e02\U5317\U533a",
    prefCode: 1
  }, {
    bigCityFlag: 1,
    cityCode: 01103,
    cityName: "\U672d\U5e4c\U5e02\U6771\U533a",
    prefCode: 1
  }, {
    bigCityFlag: 0,
    cityCode: 47382,
    cityName: "\U4e0e\U90a3\U56fd\U753a",
    prefCode: 47
  }]
};

var bigCityFlag = [];
var cityCode = [];
var cityName = [];
var prefCode = [];

for (var i = 0; i < SUCCESS.result.length; i++) {
  bigCityFlag[i] = SUCCESS.result[i].bigCityFlag;
  cityCode[i] = SUCCESS.result[i].cityCode;
  cityName[i] = SUCCESS.result[i].cityName;
  prefCode[i] = SUCCESS.result[i].prefCode;
}

console.log("BIG CITY FLAG = [ " + bigCityFlag + " ]");
console.log("CITY CODE = [ " + cityCode + " ]");
console.log("CITY NAME = [ " + cityName + " ]");
console.log("PREF CODE = [ " + prefCode + " ]");