将JSON文件读入javascript

时间:2015-11-02 23:52:15

标签: javascript json

过去三个小时我一直试图将JSON文件读入java脚本,以便我的地图符号可以通过google-maps服务读取。

然而,我有一个不完整的脚本..我无法得到我的结果。这是我的剧本:

<script>
 function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'http://127.0.0.1/irismaps/aitems.php', true); // path to file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    results = JSON.parse(response);


                 for (var i=0; i<results[0].markers.length; i++) {
            for (var b=0;b<results[0].markers[i].length;b++) {

                    //this is the object you are looking for
                    console.log(results[0].markers[i]);
                    break;

            }



    }
 });
}
</script>

JSON:

{
  "results": [
    {
      "markers": [
        {
          "longitude": "37.66653612499999",
          "latitude": "55.77875861131171",
          "title": "Industry LLC",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-82.28813722500001",
          "latitude": "23.10569357133444",
          "title": "Garden Care",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-4.792105912500006",
          "latitude": "37.875266800953554",
          "title": "Entertainers",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-73.94999999999999",
          "latitude": "40.65",
          "title": "Educators Corp.",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-0.8122895000000199",
          "latitude": "52.0443456",
          "title": "Rentacar",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "4.879416200000037",
          "latitude": "45.7783975",
          "title": "Restaurant Lucia",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "12.481953799999928",
          "latitude": "41.90567180000001",
          "title": "The Airport",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-74.0059731",
          "latitude": "40.7143528",
          "title": "Advertising Inc.",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "12.7880859375",
          "latitude": "4.565473550710291",
          "title": "Car Repairs",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "13.447265625",
          "latitude": "52.53627304145948",
          "title": "Accounting Gmbh.",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "39.638671875",
          "latitude": "24.447149589730845",
          "title": "Courier & Courier",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "10.7666015625",
          "latitude": "59.93300042374631",
          "title": "Your House A.S.",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-1.8896484375",
          "latitude": "52.482780222078205",
          "title": "M Supermarkets LLC",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "21.005859375",
          "latitude": "52.22779941887071",
          "title": "Healthy Runner S.A.",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-0.8122895000000199",
          "latitude": "52.0443456",
          "title": "Rentacar",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-0.8122895000000199",
          "latitude": "52.0443456",
          "title": "Restaurant Lucia",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "37.6173",
          "latitude": "55.755826",
          "title": "Industrie LLC",
          "icon": "img/markers/shop.png"
        },
        {
          "longitude": "-115.20111025",
          "latitude": "55.80752971122906",
          "title": "Book Group Inc.",
          "icon": "img/markers/shop.png"
        }
      ]
    }
  ]
}

2 个答案:

答案 0 :(得分:0)

您尝试加载的JSON文件基本上只是JavaScript。给你的对象一个像

这样的名字
var myJSONObject = {
    "foo": "bar"
};

将其另存为.js文件并将其加载到您的文档中。

答案 1 :(得分:0)

尝试:

  func searchBarSearchButtonClicked(searchBar: UISearchBar) {

        searchBar.resignFirstResponder()

        // Form the request URL string.
        var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&fields=items(id,snippet(title,channelTitle,thumbnails))&order=viewCount&q=\(searchBar.text)&type=video&maxResults=25&key=\(apiKey)"

        urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

        // Create a NSURL object based on the above string.
        let targetURL = NSURL(string: urlString)

        // Get the results.
        performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
            if HTTPStatusCode == 200 && error == nil {
                // Convert the JSON data to a dictionary object.
                let resultsDict = (try! NSJSONSerialization.JSONObjectWithData(data!, options: [])) as! Dictionary<NSObject, AnyObject>

                // Get all search result items ("items" array).
                let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

                // Loop through all search results and keep just the necessary data.
                for var i=0; i<items.count; ++i {
                    let snippetDict = items[i]["snippet"] as! Dictionary<NSObject, AnyObject>
                    //                    let statisticsDict = items[i]["statistics"] as! Dictionary<NSObject, AnyObject>

                    // Create a new dictionary to store the video details.
                    var videoDetailsDict = Dictionary<NSObject, AnyObject>()
                    videoDetailsDict["title"] = snippetDict["title"]
                    videoDetailsDict["channelTitle"] = snippetDict["channelTitle"]
                    videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<NSObject, AnyObject>)["default"] as! Dictionary<NSObject, AnyObject>)["url"]
                    videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<NSObject, AnyObject>)["videoId"]
                    //                    videoDetailsDict["viewCount"] = statisticsDict["viewCount"]

                    self.videosArray.append(videoDetailsDict)

                    // Reload the tableview.
                    self.tableView.reloadData()

                }

            }
            else {
                print("HTTP Status Code = \(HTTPStatusCode)")
                print("Error while loading channel videos: \(error)")
            }

        })

    }


    // MARK: Custom method implementation

    func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
        let request = NSMutableURLRequest(URL: targetURL)
        request.HTTPMethod = "GET"

        let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

        let session = NSURLSession(configuration: sessionConfiguration)

        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completion(data: data, HTTPStatusCode: (response as! NSHTTPURLResponse).statusCode, error: error)
            })
        })

        task.resume()
     }

您正在将整个文件添加到名为results的对象中,该对象包含一个名为results的数组。