How to access the specific array data after parsing the json file?

json array of objects
how to get values from json array in java
json nested arrays
read json array in java
json array length
json array of arrays
json multidimensional array
create json array in javascript

Here is the JSON:

[
  {
    "District_en": "Kowloon City",
    "Name_en": "Carpenter Road Park",
    "GIHS": "9G5i7NFpXL",
    "Court_no_en": "4",
    "Court_no_cn": "4"
  },
  {
    "District_en": "Kowl",
    "Name_en": "Road Park",
    "GIHS": "9G5i7NFaXL",
    "Court_no_en": "5",
    "Court_no_cn": "6"
  }
]

Here is my code:

func loadjson() {
        if let url = Bundle.main.url(forResource: "court", withExtension: "json"){
            do{
                let data = try Data(contentsOf: url)
                let decoder = JSONDecoder()
                let jsondata = try decoder.decode([Court].self, from: data)
                print(jsondata)
                } catch {
                print(error)
            }
        }
}

I have a localized JSON file which I know how to parse the file, but after parsing the file, I don't know how to access the specific array data inside.

When you obtain json data you need to convert it into your model Court. Court should have a special initializer that converts json data into model's properties. Like this:

struct Court: Codable {
   var district: String
   var name: String
   // and so on

   init?(json: [String: Any]) {
      guard let district = json["District_en"] as? String,
           let name = json["Name_en"] as? String else {
           return nil
       }

       self.district = district
       self.name = name
   }
}

Then you can get your models from json data:

let jsonData = try JSONSerialization.jsonObject(with: data, options: [])

if let json = jsonData as? [[String: Any]] {
      let array = json.compactMap(Court.init)

      print(array)
}
// Prints: [Court(district: "Kowloon City", name: "Carpenter Road Park"), Court(district: "Kowl", name: "Road Park")]

How to get JSON data Array value access || JSON Basics, JSON Course covers everything from start to finish to get you using JSON Lecture 11 Duration: 8:22 Posted: Mar 25, 2016 Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I have solve the problem as below, please take a reference, by using modeling and keyword self.

struct Court : Codable {

let addressCn : String?
let openingHoursCn : String?

enum CodingKeys: String, CodingKey {
    case addressCn = "Address_cn"
    case openingHoursCn = "Opening_hours_cn"

}
init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    addressCn = try values.decodeIfPresent(String.self, forKey: .addressCn)
    openingHoursCn = try values.decodeIfPresent(String.self, forKey:.openingHoursCn)
}

class TableTableViewController: UITableViewController {

var court = [Court]()

override func viewDidLoad() {
    super.viewDidLoad()
    fetchjson()
}


override func tableView(_ tableView: UITableView, numberOfRowsInSection    section: Int) -> Int {
    return court.count
}


func fetchjson() {
    if let url = Bundle.main.url(forResource: "facility-bkbc", withExtension: "json"){
        do{
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            self.court = try decoder.decode([Court].self, from: data)
            print(court)
            self.tableView.reloadData()
        }catch{ print(error)}}}

}

JSON Array – REST API Tutorial, JSON array can store string, number, boolean, object or other array inside JSON array. Get value at specific index location in array Use the delete keyword to delete items from an array: Introduction to JSON · JSON Syntax · JSON Data Types · JSON Schema · JSON Objects · JSON Array · JSON.parse() · JSON.​stringify  Retrieve Data from Arrays Some JSON strings will have data found in arrays instead of just nested JSON objects. In the example, this would the 'contents' data. If you were accessing this information using JSON Dot Notation, then you would do something like the following: echo contents[0].productID; \\ output: "34"

It's like any other type of array. For example:

if let decodedData = jsonData{
    print(decodedData.first)

    print(decodedData[1].name)
}

In the first print you will get the "Carpenter Road Park" object printed. In the second case it will print: "Road Park" (supposing you decoded "Name_en" as "name".

JSON Arrays, AJAX Intro AJAX XMLHttp AJAX Request AJAX Response AJAX XML File AJAX In JSON, array values must be of type string, number, object, array, boolean or null. You access the array values by using the index number: Use the delete keyword to delete items from an array: Copyright 1999-2020 by Refsnes Data. In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details.So I modified the program a little bit. import json input_file = open ('stores-small.json') json_array = json.load(input_file) store_list = [] for item in json_array: store_details = {"name":None, "city":None} store_details['name'] = item['name'] store_details['city'] = item

How to read/parse JSON array using Java?, To read an array from a JSON file using a Java program −. Instantiate the JSONParser class of the json-simple library. JSONParser jsonParser  Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. Arrays in JSON Objects. Arrays can be values of an object

JavaScript JSON Parsing, Whereas an example of JSON array would look something like this: In JavaScript, you can easily parse JSON data received from the web server using to convert this JSON string into a JavaScript object and access individual values using  Using the VBA JSON library, you certainly can import JSON formatted files into MS Access. The idea is to consider JSON data as a collection of dictionaries and Visual Basic provides the collection and dictionary as data structures. Below are the steps: Build a table to match the structure of expected JSON data.

How to Use JSON Data with PHP or JavaScript – Tania Rascia, From here out, we'll put all JSON data into its own .json file. This way, we Aragorn. I can access all the data in the array with a foreach loop. Now we'll use JavaScript built in JSON.parse() function to decode the string. data  How to read Json array data using JsonArray? This page shows how to read Json array data using JsonArray object. Note: Refer How to read Json data using JsonReader? page for dependent libraries. Here is the input json file:

Comments
  • That's very basic stuff. Please read Swift Language Guide: Collection Types and Swift Language Guide: Structs and Classes
  • please add the Court struct or model you are using
  • Thanks for your help, but i cannot cast the data to dictionary, Cast from '[Court]' to unrelated type '[[String : AnyObject]]' always fails.I am trying to solve this now
  • I changed the Court's initializer above. Check it now. If initializer has parameter [String: Any], you should cast Any type to String explicitly.