samedi 9 mai 2015

Extracting json array from http response

I'm new to AngularJS for a project and I'm trying to extract a json array from a http response to use in a list.

The response looks like this:

{"DFH0XCMNOperationResponse":{"ca_return_code":0,"ca_inquire_request":{"ca_last_item_ref":150,"ca_item_count":15,"ca_cat_item":[{"ca_cost":"002.90","in_stock":119,"ca_description":"Ball Pens Black 24pk","on_order":0,"ca_department":10,"ca_item_ref":10},{"ca_cost":"002.90","in_stock":6,"ca_description":"Ball Pens Blue 24pk","on_order":50,"ca_department":10,"ca_item_ref":20}],"ca_list_start_ref":0},"ca_response_message":"+15 ITEMS RETURNED","ca_request_id":"01INQC"}}

The code for the resource and request looks like this:

.factory('getCatalog', ['$resource', function($resource){
    return $resource('catalogmanagertest/v1/apps/bca45894-92f7-49dc-ae54-b23b89ab6c73/catalog', {}, {query: {method:'POST'}});
}]);

And the controller code relevant looks like this:

angular
.module('catalogController', ['ngMaterial', 'ngResource'])
.controller('catalogController', ['$scope', 'getCatalog', 'catalog', function($scope, getCatalog, catalog) {
    $scope.debug = getCatalog.query(); // set scope catalog to array from zOS
    $scope.catalog = catalog.ca_cat_item;
    $scope.message = "This is a test order message";
this.tiles = buildGridModel({
        icon : "avatar:svg-",
        title: "",
        cost: "€",
        background: "",
        stock: ""
    });
    function buildGridModel(tileTmpl){
        var it, results = [ ];

        var tmp = $scope.debug.DFH0XCMNOperationResponse.ca_inquire_request.ca_cat_item;
        console.log(tmp);

The next to last line is what I'm having trouble with. How do extract the expected array? I get the newbie error when I do the console.log:

TypeError: Cannot read property 'ca_inquire_request' of undefined

Search deep nested JSON

I am working on a solution where I need to search for an element in a deeply nested JSON by its id. I have been advised to use underscore.js which I am pretty new to.

After reading the documentation http://ift.tt/1Ro26UY , I tried to implement the solution using find, filter and findWhere.

Here is what I tried using find :

 var test = {
    "menuInputRequestId": 1,
    "catalog":[
      {
        "uid": 1,
        "name": "Pizza",
        "desc": "Italian cuisine",
        "products": [
          {
            "uid": 3,
            "name": "Devilled chicken",
            "desc": "chicken pizza",
            "prices":[
              {
                "uid": 7,
                "name": "regular",
                "price": "$10"
              },
              {
                "uid": 8,
                "name": "large",
                "price": "$12"
              }
            ]
          }
        ]
      },
      {
        "uid": 2,
        "name": "Pasta",
        "desc": "Italian cuisine pasta",
        "products": [
          {
            "uid": 4,
            "name": "Lasagne",
            "desc": "chicken lasage",
            "prices":[
              {
                "uid": 9,
                "name": "small",
                "price": "$10"
              },
              {
                "uid": 10,
                "name": "large",
                "price": "$15"
              }
            ]
          },
          {
            "uid": 5,
            "name": "Pasta",
            "desc": "chicken pasta",
            "prices":[
              {
                "uid": 11,
                "name": "small",
                "price": "$8"
              },
              {
                "uid": 12,
                "name": "large",
                "price": "$12"
              }
            ]
          }
        ]
      }
    ]
  };

var x = _.find(test, function (item) {
    return item.catalog && item.catalog.uid == 1;
});

And a Fiddle http://ift.tt/1ciHYTM

The issue I faced is that these functions check the top level of the JSON and not the nested properties thus returning undefined. I tried to use item.catalog && item.catalog.uid == 1; logic as suggested in a similar question Underscore.js - filtering in a nested Json but failed.

How can I find an item by value by searching the whole deeply nested JSON?

EDIT:

The following code is the latest i tried. The issue in that is that it directly traverses to prices nested object and tries to find the value. But my requirement is to search for the value in all the layers of the JSON.

var x = _.filter(test, function(evt) {
    return _.any(evt.items, function(itm){
        return _.any(itm.outcomes, function(prc) {
            return prc.uid === 1 ;
        });
    });
});

History API - Ajax pages + Json

I have a structure of my site like this IMAGE
I'm trying to create some page transition with ajax & history API

CODE:

history.pushState(null, null, "/members/" + dataLink + ".php" ); // update URL
console.log(dataLink);
$(".ajax-container").load('/members/single.php', function(){
     fillPage(dataLink); // load datas from json
});

Everything works fine, I can load the page correctly with datas but now I have to implement the behavior of the back button (using history api / popstate )but I've no idea how to do that because every member-page in filled with data from json.

$(window).bind('popstate', function() {
 // what inside here? It should call the previous page + the data from json like the previous ajax call
});

Any ideas?

Football API 2015 json

I need one api that give's me information about american cup 2015. Teams, players, livescore,results. If is posibble in json format.

Thanks

Getting JSONException in decoding the JSON string

I am trying to decode a JSON response string which is an image encoded.I am getting JSON.typeMismatch error.This is JSON response

   {"0":"5","id":"5","1":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/4QCYRXhpZgAASUkqAAgAAAACADEBAgAHAAAAJgAAAGmHBAAB\r\nAAAALgAAAAAAAABHb29nbGUAAAQAAJAHAAQAAAAwMjIwCZAHACwAAABkAAAAAqAEAAEAAACAAQAA\r\nA6AEAAEAAAByAQAAAAAAAAoqCAEQARgAIAAoADAAOABAAEgBUABYAGH3CrBNW3Nv5qQ5Uf6\/wD9lleXGSQ2B859T+KmHDzfMFleUEQYYrC5\r\n9U8o7LK8io8zFFJYhZXlNEGM3LTNj5R6LC8jIHIidRu\/qorxK631\/BZXk7DycIhlTvN\/4uPv1RrA\r\nPPnWF5ds8nYEi4V\/P9FO6RufRZXlT8j8h+IPzh51s9B+JVecVunFYcG4Ju03BgncGy8vJ7jfxivI\r\n8n\/\/2Q==\r\n"}

My android code for decoding is

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet("http://ift.tt/1InV8g5"); 
                                // replace with your url

        HttpResponse response;
        try {
            response = client.execute(request);



            String responseStr = EntityUtils.toString(response.getEntity());

             try {
                JSONArray jArray = new JSONArray(responseStr);
                for(int i=0;i<jArray.length();i++){
                 JSONObject json_data = jArray.getJSONObject(jArray.length()-i-1);
                 String img="";//json_data.getString("image");
                 Toast.makeText(getApplicationContext(), img, 
                           Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {

                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

My log shows the following errors

 W/System.err(19280): org.json.JSONException: Value         {"id":"5","image":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/4QCYRXhpZgAASUkqAAgAAAACADEBAgAHAAAAJgAAAGmHBAAB\r\nAAAALgAAAAAAAABHb29nbGUAAAQAAJAHAAQAAAAwMjIwCZAHACwAAABkAAAAAqAEAAEAAACAAQAA\r\nA6AEAAEAAAByAQAAAAAAAAoqCAEQARgAIAAoADAAOABAAEgBUABYAGABaAFwAHgBgAEBiAEBkAEB\nx2nba+9uA3AXcit0Q3ZbeHN6i3ynfr+A24L3hROHM4lPi2+Nj4+vkc+T8\r\n5YTmDeaW5x\/nqegy6LzpRunQ6lvq5etw6\/vshu0R7ZzuKO6070DvzPBY8OXxcvH\/8ozzGfOn9DT0\r\nwvVQ9d72bfb794r4Gfio+Tj5x\/pX+uf7d\/wH\/Jj9Kf26\/kv+3P9t\/\/9kZXNjAAAAAAAAAC5JRUMg\r\nNjE5NjYtMi0xIERlZmF1bHQgUkdCIENvbG91ciBTcGFjZSAtIHNSR0IAAAAAAAAAAAAAAAAAAAAA\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

 05-09 18:19:02.196: W/System.err(19280):   at org.json.JSON.typeMismatch
  (JSON.java:111)
 05-09 18:19:02.196: W/System.err(19280):   at org.json.JSONArray.<init>

 (JSONArray.java:91)
 05-09 18:19:02.196: W/System.err(19280):   at org.json.JSONArray.<init>

  (JSONArray.java:103)
   05-09 18:19:02.196: W/System.err(19280):     at        com.threepixels.tester.MainActivity.onCreate(MainActivity.java:56)
   05-09 18:19:02.196: W/System.err(19280):     at   android.app.Activity.performCreate(Activity.java:5133)
      05-09 18:19:02.206: W/System.err(19280):  at andro    id.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        05-09 18:19:02.206: W/System.err(19280):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)
     05-09 18:19:02.206: W/System.err(19280):   at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)

how to get values from json with unknown ammount of given elements

Given this json as example:

{"offspring0":"John"},
{"offspring1":"Anna"},
{"offspring2":"Peter}

I can know how many offspring are there with:

offspringCount = (jsonString.match(/offspring/g) || []).length; //jsonString is the json above

This would return 3. Now, how can i get the value of all those offsprings? I have tried:

json = JSON.parse(jsonString);
alert(json[0].offspring[0]);

But this throws Uncaught TypeError: Cannot read property '0' of undefined because offspring is not an array.

I also tried:

alert(json[0]."offspring0");

But getting Uncaught SyntaxError: Unexpected string

My intention is to loop through all the offspring[number] and get the values, was expecting something like this:

for(x=0; x<offspringCount; x++){
    alert(json[0].offspring[x]);
}

Note i do not handle the making of the JSON, i only request it to a server.

JSON parser failing to Convert my Strings

I am working on an Android App that Collects certain information from a PHP MysQl Server, but I am facing a problem with JSON Parser, sometimes it works sometimes it does not work, it gives me these Errors:

    E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Failed of type java.lang.String cannot be converted to JSONObject
    Caused by: java.lang.NullPointerException

And the Code thats producing the Errors:

try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password));
                params.add(new BasicNameValuePair("fname", fname));
                params.add(new BasicNameValuePair("lname", lname));
                params.add(new BasicNameValuePair("email", email));
                params.add(new BasicNameValuePair("city", city));
                params.add(new BasicNameValuePair("nrc", nrc));
                params.add(new BasicNameValuePair("dob", dob));
                params.add(new BasicNameValuePair("cell", cell));




                Log.d("username", username);
                Log.d("password", password);
                Log.d("fname", fname);
                Log.d("lname",lname );
                Log.d("email",email );
                Log.d("city",city );
                Log.d("nrc",nrc );
                Log.d("dob",dob );
                Log.d("cell",cell );



                Log.d("request!", "starting");

                //Posting user data to script
                JSONObject json = jsonParser.makeHttpRequest(
                        REGISTER_URL, "POST", params);

                // full json response
                Log.d("Registering attempt", json.toString());


                // json success element
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    Log.d("User Profile Created!", json.toString());

The NullException is being caused by the Line:

    Log.d("Registering attempt", json.toString());

Populating mxml with JSON data containing urls

I just started learning Flex today. I faced a problem. I have some JSON data returned from my webservice, like this:

[{"id":"34","url":"im3.png","uid":"1","pr":"1"},{"id":"33","url":"im2.jpg","uid":"1","pr":"0"},{"id":"32","url":"im1.jpg","uid":"1","pr":"1"}]

I can decode it and store in array which populates my DataGrid.

<mx:DataGrid id="prGallery" left="25" right="25" top="25" bottom="25" dataProvider="{prDB}">

prDB is intialized "on load".

Everything works fine but... I would like to display images out of those URLs (images are stored on my server under xxxxx.xx/url.

Storing tags like <img src="xxxxx.xx/url"/> obviously doesn't work. So here come my questions:

  1. Firstly, is it a good idea to use DataGrid for displaying images? (Even though I couldn't see the result I think it's not.)
  2. What other component should I use in order to populate it with unknown number of records. (rows contain both text and image).

Bootstrap Table, data url

HI i got trouble with this. yesterday i found bootstrap table but i got a problem. first the code looks like this:

$(function () {
    var $result = $('#eventsResult');

    $('#eventsTable').on('all.bs.table', function (e, name, args) {
        console.log('Event:', name, ', data:', args);
    })
    .on('click-row.bs.table', function (e, row, $element) {
        $result.text('Event: click-row.bs.table');
    })
    .on('dbl-click-row.bs.table', function (e, row, $element) {
        $result.text('Event: dbl-click-row.bs.table');
    })
    .on('sort.bs.table', function (e, name, order) {
        $result.text('Event: sort.bs.table');
    })
    .on('check.bs.table', function (e, row) {
        $result.text('Event: check.bs.table');
    })
    .on('uncheck.bs.table', function (e, row) {
        $result.text('Event: uncheck.bs.table');
    })
    .on('check-all.bs.table', function (e) {
        $result.text('Event: check-all.bs.table');
    })
    .on('uncheck-all.bs.table', function (e) {
        $result.text('Event: uncheck-all.bs.table');
    })
    .on('load-success.bs.table', function (e, data) {
        $result.text('Event: load-success.bs.table');
    })
    .on('load-error.bs.table', function (e, status) {
        $result.text('Event: load-error.bs.table');
    })
    .on('column-switch.bs.table', function (e, field, checked) {
        $result.text('Event: column-switch.bs.table');
    })
    .on('page-change.bs.table', function (e, size, number) {
        $result.text('Event: page-change.bs.table');
    })
    .on('search.bs.table', function (e, text) {
        $result.text('Event: search.bs.table');
    });
});
<div class="alert alert-success" id="eventsResult">
    Here is the result of event.
</div>
<table id="eventsTable"
       data-toggle="table"
       data-height="300"
       data-url="http://ift.tt/1bFI5ID"
       data-pagination="true"
       data-search="true"
       data-show-refresh="true"
       data-show-toggle="true"
       data-show-columns="true"
       data-toolbar="#toolbar">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="name">Name</th>
        <th data-field="stargazers_count">Stars</th>
        <th data-field="forks_count">Forks</th>
        <th data-field="description">Description</th>
    </tr>
    </thead>
</table>

And this works when i insert into my site but when i change daa url to this; http://ift.tt/1JWjDla Noothing, i changed data field to mid, title, author since that is in my json.

http://ift.tt/1bFI5YR IS there any way i can display that mid author and title in table?

PS: sorry for my bad english.

Read complex JSON Data in Swift

I've been trying to read this complex JSON Data in swift but with no luck and results.

{
  "feed": {
    "entry": [
      {
        "media$group": {
          "media$content": [
            {
              "url": "http://..../photo.png"
            }
          ]
        }
      }
    ]
  }
}

Please help me to write the code in swift.

Facebook get JSON datas android

i'm using this method directly from Facebook Developer to get users information after login, i need to get username, userid and email

public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(
                                    JSONObject object,
                                    GraphResponse response) {
                                // Application code


                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email");
                request.setParameters(parameters);
                request.executeAsync();

how should i do to get the JSON information and store it in Public variable in my document, to use it in other function ?

How would you implement better serilization/deserialization in Haxe?

The server I use at work (out of my control) always uses XML in the responses/requests.

Haxe has pretty good Json support but not really for XML. You have to traverse the xml elements and it's not all that efficient. I'm trying to make my life easier because the client's service always uses XML.

I'd love to be able to take in XML and output an object easily like in Java.

The trouble is, I have no clue how I would even go about this.

Is it worth going down this road? I suppose I could take a look at the Java one and try to re-implement it in Haxe?

Would embedding an external one be a better option? Any suggestions?

Has anyone had experience with this library: http://ift.tt/1Qw1TOh

Or would just extending the already-implemented parts of the library be the most practical thing to do: http://ift.tt/1Qw1UBP

Json in Android : Unexpected character (<) at position 0

I am trying to use Json for an android online db connection. Problem is no matter what i try i get the ever so popular Unexpected character (<) at position 0 error.

here is my method:

 public void getData(){
    String result = "";
    InputStream isr = null;

    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http:link to my file.php");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        isr = entity.getContent();
    }
    catch(Exception e){
        Log.e("log_tag", "Error in http connection " + e.toString());
        resulString="Couldn't connect to database";
    }
    //convert response to string
    try{
        BufferedReader reader = new BufferedReader(newInputStreamReader(isr,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        isr.close();

        result=sb.toString();
    }
    catch(Exception e){
        Log.e("log_tag", "Error  converting result "+e.toString());
    }

    //parse json data
    try {
        String s = "";
        JSONParser parser_obj = new JSONParser();
        JSONArray jArray = (JSONArray) parser_obj.parse(result.toString());

        for(int i=0; i<jArray.length();i++){
            JSONObject json = jArray.getJSONObject(i);
            s = s +
                    "Id : "+json.getInt("Id")+" Name: "+json.getString("ShopName")+"\n"+
                    "Icon : "+json.getInt("ShopIcon")+"Description:"+json.getString("ShopDesc")+"\n\n";
        }

        resulString=s;

    } catch (Exception e) {
        // TODO: handle exception
        Log.e("log_tag", "Error Parsing Data "+e.toString());
    }

}

tried both get and post methods heres my php file:

!php1

the connection is established but theres no result and loggcat displays that error. Can you help me please?

Pass Stringbuilder message from Json [MVC-Controller]and render it in view

I am trying to pass a StringBuilder message as an extra data back to ajax call but I am failing to manipulate it in client side. Below is the way I append message to StringBuilder and pass it back.

StringBuilder retMessage=new StringBuilder();
retMessage.Clear().AppendLine("Successfully added the user!"); 
//Clear will done only on Success otherwise will append the different errorMessage using AppendLine
return Json(new { result = valid, message = retMessage });

On the ajax Success I tried retrieving it as below but with no success.

 success: function (data) {
              if (data.result) {
                    ResetForm('#frmChangePwd');
                    console.log(data.message);
              },
 }

Below are images showing how it is passed from server side and how it is obtained in client side!!

Server Side return

Server Side return

Client Side retrieval

Client Side retrieval

Can anyone tell me how to retrieve message in client side and display it in view?

how to get estimated json value in asp.net

  • How to pick the value of "estimatedResultCount" from json data
  • I tried this code and getting but its not the right way
  • How to get a particular node value from json data
  • I dont know how to get the value using json

    string link = txtweb.Text.Trim();
            string strurl = "http://ift.tt/1RnGYOS:" + link;
            StreamReader stream = objm.URLServerRequest(strurl);
    
            string myResponse = stream.ReadToEnd();
            // var stuff = JsonConvert.DeserializeObject(myResponse);
            // string backlinks = stuff.responseData.cursor.estimatedResultCount;
    
    
    
    
    
            string output = myResponse.Substring(myResponse.IndexOf(@"estimatedResultCount") + @"/**".Length);
            string str = output.Remove(0, 20);
    
            string value1 = str.Substring(0, str.IndexOf(",") + 1);
            //str = str.Remove(str.IndexOf(','));
    
            string value3 = value1.Remove(value1.Length - 2);
    
    

    }

json data

 {
       "responseData":{
          "results":[
             {
                "GsearchResultClass":"GwebSearch",


    "unescapedUrl":"http://ift.tt/1QvZByu",
                "url":"http://ift.tt/1QvZByu",
                "visibleUrl":"www.homeocare.in",


    "cacheUrl":"http://ift.tt/1xLj0zV

    \u003dcache:E7xF9dtFWgIJ:www.homeocare.in",
                "title":"Homeopathy Clinics in Hyderabad 

    - Homeopathy Treatment",
                "titleNoFormatting":"Homeopathy Clinics 

    in Hyderabad - Homeopathy Treatment",
                "content":"Homeocare International - 

    World Class Homeopathy Clinic in India provides 

    \ninformation on causes, symptoms, and Homeopathy 

    treatment of various \ndiseases."
             },
             {
                "GsearchResultClass":"GwebSearch",


    "unescapedUrl":"http://ift.tt/1RnH1dp

    l",


    "url":"http://ift.tt/1QvZDX9",
                "visibleUrl":"www.homeocare.in",


    "cacheUrl":"http://ift.tt/1xLj0zV

    \u003dcache:zrjNDKonZY0J:www.homeocare.in",
                "title":"Homeocare International | 

    Contact Us",
                "titleNoFormatting":"Homeocare 

    International | Contact Us",
                "content":"To get best Homeopathy 

    treatment Contact Homeocare International through 

    \nphone or fill contact form. We have branches all 

    over South India."
             },
             {
                "GsearchResultClass":"GwebSearch",


    "unescapedUrl":"http://ift.tt/1RnGZ56.

    html",


    "url":"http://ift.tt/1QvZByx",
                "visibleUrl":"www.homeocare.in",


    "cacheUrl":"http://ift.tt/1xLj0zV

    \u003dcache:oPJKzW6sHOkJ:www.homeocare.in",
                "title":"Homeocare International Reviews 

    / Testimonials",
                "titleNoFormatting":"Homeocare 

    International Reviews / Testimonials",
                "content":"Homeocare International 

    Reviews / Testimonials for Happy Patient. We pride 

    \nourselves on excellent service, and our reviews 

    show it!"
             },
             {
                "GsearchResultClass":"GwebSearch",


    "unescapedUrl":"http://ift.tt/1RnGZ5a

    l",


    "url":"http://ift.tt/1QvZByC",
                "visibleUrl":"www.homeocare.in",


    "cacheUrl":"http://ift.tt/1xLj0zV

    \u003dcache:gqHnM_Tg0hcJ:www.homeocare.in",
                "title":"Homeopathy Treatment for 

    Arthritis | Arthritis Treatment",
                "titleNoFormatting":"Homeopathy Treatment 

    for Arthritis | Arthritis Treatment",
                "content":"Get Homeopathy Treatment for 

    arthritis and rheumatoid arthritis at Homeocare 

    \nInternational provides safe and effective remedies 

    with no side effects."
             }
          ],
          "cursor":{
             "resultCount":"176",
             "pages":[
                {
                   "start":"0",
                   "label":1
                },
                {
                   "start":"4",
                   "label":2
                },
                {
                   "start":"8",
                   "label":3
                },
                {
                   "start":"12",
                   "label":4
                },
                {
                   "start":"16",
                   "label":5
                },
                {
                   "start":"20",
                   "label":6
                },
                {
                   "start":"24",
                   "label":7
                },
                {
                   "start":"28",
                   "label":8
                }
             ],
             "estimatedResultCount":"176",
             "currentPageIndex":0,


    "moreResultsUrl":"http://ift.tt/1RnH1dr

    \u003dutf8\u0026ie\u003dutf8\u0026source\u003duds

    \u0026start\u003d0\u0026hl\u003den\u0026q

    \u003dsite:www.homeocare.in",
             "searchResultTime":"0.23"
          }
       },
       "responseDetails":null,
       "responseStatus":200
    }

Retrieving JSON in Web Service

I have recently started working on WebServices and I don't completely know if it is even possible. I am passing JSON string to WCF Web Service and I want to know if there is anyway that Web Service can retrieve JSON string and return data against the retrieved string?

How would I organize the dicts into a list using this websites API?

For a project I am using this websites API:

http://ift.tt/1KsnbZf

I am having difficulty separating the dicts into a list. This is my code for the project so far:

import json

import urllib.request

import statistics

    def get_website_stats(website):
    url = 'http://ift.tt/1zSi44A'+ website +'&output=json'
    lines = urllib.request.urlopen(url).readlines()
    list_of_strings = []
    for obj in lines:
        list_of_strings.append(obj.decode('utf-8').strip('\n'))
    merged_string = ' '
    for string in list_of_strings:
        if string not in ('[', ']'):
            merged_string += string
    return json.loads(merged_string)

    symbol=input("What is the website name? (Do not include www)")
    stats = get_website_stats(symbol)
    print(stats['bro'])

If you read through the API it is obvious I am trying to print out the browser the user of the website is using but instead I get an error:

TypeError: list indices must be integers, not str

Could anyone help me organize the dicts into the list properly? I think the problem is I am appending an entire line into each element of the list.

Need help iterating through a complex Json (no jquery)

I need to create a symfony2 bundle that generates a sidebar from a YAML file

I created this YAML structure

Sidebar:
  - Frontpage:
        - Dashboard:
            _icon: 'icon-home'
            _route: 'link'
  - Actions:
          - My_Likes:
              _icon: 'icon-dislike'
              _route: 'link'
          - My_Dislikes:
              _icon: 'icon-home'
              _route: 'link'
  - Interests:
          - Add_Interest:
              _icon: 'icon-home'
              _route: 'link'

which returns this JSON as a response.

{
  "Sidebar": [
    {
      "Frontpage": [
        {
          "Dashboard": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Actions": [
        {
          "My_Likes": {
            "_icon": "icon-dislike",
            "_route": "link"
          }
        },
        {
          "My_Dislikes": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    },
    {
      "Interests": [
        {
          "Add_Interest": {
            "_icon": "icon-home",
            "_route": "link"
          }
        }
      ]
    }
  ]
}

Using ajax, the json is returned on the 'data' variable on the client side

Sidebar.model.request(function(data)
{ 
    for(var a=0; a< data.Sidebar.length; a++ )
    {
       console.log(data.Sidebar[a]);
    }
});

I need to find a way to iterate through the parents and find the corresponding children. I only need help creating the for loop, so a solution using console.log(data[stuff]); would be enough


EDIT: here is the adjusted snippet of Daniel Rosano's code

    Sidebar.model.request(function(data)
    { 
        //Get Sidebar items
        var SidebarItems = data.Sidebar;

        //Find Categories in Sidebar Items
        for(var a=0; a< SidebarItems.length; a++ )
        {
            var category = SidebarItems[a];

            //Get Category name and append it to sidebar
            var category_name = getSubitemName(category);
            Sidebar.view.renderCategory(category_name);

            //find subitems in categories
            for(var b=0; b < category[category_name].length; b++)
            {
                var button = category[category_name][b];
                var button_name = getSubitemName(button);

                var button_attributes = button[button_name];

                console.log(button_attributes['_icon']);
                Sidebar.view.renderButton(button_name);
            }
        }

        function getSubitemName(parent)
        {
            for(child in parent)
            {
                return child.toString();
            }
        }
    });

this is the result, thanks Daniel

Obviously incomplete but this is the result

How to pass a large json data from view to controller, and save it in the server?

My situation is, i have a file which is formate of .CSV, i use javascript to convert it into json, this is successful.

But in another view, i need this json data in the "data-source",

<div id="map" data-source="/Test/flickr_Test_view.csv"></div>

so i think i should pass this json data from view to controller in ajax, and save this data as a .json file in server, then i can succeed use it above

Can some body help me how to pass a large json data from view to controller? Thank you!

Retrofit - get some parameters from callback without creating a POJO

I'm using retrofit and in my response i get this json:

{
   'email':'some@email.com',
   'is_valid':'0'
}

I know that i can create a class with these fields and ask for retrofit to map and deserialize it as object with

someMethod(callback<ThatClass> callback)

but i want to know if i can have these field as some variables directly in my callback and not with POJO creation?

like this:

someMethod(callback<String email, int is_valid> callback)

How to send data saved in SQLite db in android to remote server using HTTP post in android

I need to take the data from local db and send data in the below format

{"Info":[{"flag":"4","app_mother_id":"100","app_emp_id":"10","device_id":"d4544","mother_gvt_id":"mgid1524","name":"anvi"}
,
{"flag":"4","app_mother_id":"110","app_emp_id":"12","device_id":"did5442","mother_gvt_id":"mid1652","name":"swathi"}]}

am using below code to fetch data from local db and post it to server
Cursor cursor = DBHelper.getInstance(this).getList();
        JSONObject jObject = new JSONObject();;
        JSONArray jArray = new JSONArray();

        while(cursor.moveToNext()) {

            jObject = new JSONObject();

        jObject.put("name", cursor.getString(cursor.getColumnIndex("mother_name")));
        jObject.put("mother_gvt_id", cursor.getString(cursor.getColumnIndex("registration_id")));
         jObject.put("device_id", "");
          jObject.put("app_emp_id", cursor.getString(cursor.getColumnIndex("registration_id")));
          jObject.put("app_mother_id", cursor.getString(cursor.getColumnIndex("registration_id")));
          jObject.put("flag", "1");

            jObject.put("benInfo", jArray);
            jArray.put(jObject);
        }

am posting the log please help me in solving the issue.

  05-09 06:52:36.700: E/AndroidRuntime(1465): Caused by: java.lang.StackOverflowError
05-09 06:52:36.700: E/AndroidRuntime(1465):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:147)
05-09 06:52:36.700: E/AndroidRuntime(1465):     at java.lang.StringBuilder.append(StringBuilder.java:216)
05-09 06:52:36.700: E/AndroidRuntime(1465):     at org.json.JSONStringer.beforeValue(JSONStringer.java:412)
05-09 06:52:36.700: E/AndroidRuntime(1465):     at ## Heading ##org.json.JSONStringer.open(JSONStringer.java:178)
05-09 06:52:36.700: E/AndroidRuntime(1465):     at org.json.JSONStringer.array(JSONStringer.java:139)
05-09 06:52:36.700: E/AndroidRuntime(1465):     at org.json.JSONArray.writeTo(JSONArray.java:600)

GSON is trying to deserialize a String to double

I'm using Retrofit with a GSON converter to obtain JSON from a RESTful Web Service and when GSON tries to convert a JSON object to POJO I'm getting the error:

retrofit.Converter:conversionException: com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: "610/182"

This element corresponds to a String variable in my Java Object:

@Expose
@SerializedName("code")
private String code;
...

And the JSON Object is:

{"code":"610/182", ...}

I added a converter to my RestAdapter like this:

    restAdapter = new RestAdapter.Builder()
            .setEndpoint(URL_BASE)
            .setClient(new OkClient(getClient()))
            .setConverter(new GsonConverter(gson))
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    api = restAdapter.create(ApiRest.class);

Why GSON is trying to convert a String into a double?

How to Get the first value of same element in Json

I want to pick the first value of 'Code' element from following Json Payload. I am using following website to try this out. http://ift.tt/1auydud

Json Payload:

   {
    "TotalAccounts": {
        "Account": [
            {
                "Code": 123,
                "Account": {
                    "Name": {
                        "Initials": null
                    },
                    "Address": {
                        "Street": "ABC"
                    }
                },
                "ContactInformation": {
                    "Email": "ABC@gmail.com"
                },
                "DunningLevelCode": "R0"
            },
            {
                "Code": 456,
                "Account": {
                    "Name": {
                        "Initials": null
                    },
                    "Address": {},
                    "CustomFields": null
                },
                "ContactInformation": {
                    "Email": "ABC@@gmail.com",
                    "Phone": null,
                    "Mobile": null,
                    "Fax": null
                },
                "DunningLevelCode": "abc"
            }
        ]
    }
}

The Json path i am using is below:

$..Code

Result:

[123,456]

Expected Result:

[123]

Need help.

How to Get data from JSON request in struts2

I'm trying to get data from a JSON request in Apache Struts 2.
I've tested with this url: http://ift.tt/1lseVxE.
In StrutsJsonClientAction.java file, line

System.out.println(result);

prints this to the console:

{ "time": "12:04:12 PM", "milliseconds_since_epoch": 1431086652240, "date": "05-08-2015"}

I want to know how to show this result in result.jsp

Today, I found there is resttemplate can use in spring,I want to know are there the tools like restemplate in struts2 that I can use??

My current solution: StrutsJsonClientAction.java

package com.example.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

public class StrutsJsonClientAction extends ActionSupport{

    private static final long serialVersionUID = 1L;

    private final String url="http://ift.tt/1lseVxE";

    public String execute() throws Exception {

        HttpServletRequest request= ServletActionContext.getRequest();

        request.setCharacterEncoding("utf-8");

        URL myUrl = new URL(url);
        //System.out.println(myUrl.toString());
        HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection(); 
        connection.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8")); 
        String result=""; 
        String temp=null;

        while ((temp=reader.readLine())!= null) { 
            result=result+temp;
        } 

        System.out.println(result);

        return SUCCESS;
    }

}

file struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://ift.tt/1tkDVrF">
<struts>
    <package name="struts2" extends="struts-default">  
        <action name="GoToGetApi" class="com.example.action.StrutsJsonClientAction">  
            <result>/resault.jsp</result>  
        </action>  
    </package>  
</struts>    

Nesting ng-repeat at single level of DOM

I have nested collections, as follows:

[
  {
    name:    "foo",
    members: ["foo1","foo2"]
  }, {
    name:    "bar",
    members: ["bar1","bar2","bar3"]
  }, {
    name:    "qux",
    members: []
  }
]

From this, I would like to generate the following markup:

<tbody>
  <tr>
    <th scope="row" rowspan="2">foo</th>
    <td>foo1</td>
  </tr><tr>
    <td>foo2</td>
  </tr><tr>
    <th scope="row" rowspan="3">bar</th>
    <td>bar1</td>
  </tr><tr>
    <td>bar2</td>
  </tr><tr>
    <td>bar3</td>
  </tr>
</tbody>

It would also be acceptable to repeat the <th> cells in each row, if rowspan proves too awkward to work with:

<tbody>
  <tr>
    <th scope="row">foo</th>
    <td>foo1</td>
  </tr><tr>
    <th scope="row">foo</th>
    <td>foo2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar1</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar3</td>
  </tr>
</tbody>

What is the idiomatic way to accomplish a task like this using AngularJS? In particular, I'm struggling to see how one can perform a nested ng-repeat at a single level of the DOM (i.e. on the <tr> element).

How to serialize this class into XML or JSON

I have a list of objects derived from a class named "Campus" which contains two strings, one int and two lists : one for "Students", the other is for "Teachers", before closing the program, I want to save the campus objects and of course the "Student" and "Teachers" objects contained on their lists, I want to serialize those data in an XML or JSON format or even anything else then store the result in a file.

Can somebody give me the fastest way to do the serialization with a library (that is not heavy as boost) in XML or JSON or another solution. When it comes to deal with JSON or XML serialization, I don't know what to do ! EDIT: is this feasible with RapidJSON ?

class Campus
{
private:
    std::string city;
    std::string region;
    int capacity;
    std::list<Student> students;
    std::list<Teacher> teachers;
}

class Student
{
private:
    int ID;
    std::string name;
    std::string surname;
}

class Teacher
{
protected:
    int ID;
    std::string name;
    std::string surname;
};

Json table update after certain date

At the moment i have this code

// JavaScript Document

   $.ajax({

      type: 'GET',
      crossDomain: true,
      dataType: 'json',

      url: 'http://ift.tt/1JWasRJ',

      success: function (json) {
           //var json = $.parseJSON(data);
           for(var i =0;i < json.results.length;i++) {
             var title = json.results[i].name;
             var venue = json.results[i].venue;
                 var date = json.results[i].date;
                    var button = "<button class='btn btn-info' data-url='"+(i+1)+".html'>Compare</button>";

             $("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".btn.btn-info").click(function(){
   location.href = $(this).attr("data-url");
});
           }
     },
     error: function(error){
          console.log(error);
     }
   });

This appends the URL to a table. However as you can see this code here data-url='"+(i+1)+".html' created the button with an increment of 1 on the amount of buttons listed.

The issue is, this api is updating every 5 hours. When the event passes, The buttons need to really be updated. Otherwise the whole site breaks.

So the question is how could i go around making the links unique and update when an event passes? whilst im writing this i believe i could just use the Date function, So the code would be

data-url='"+date+".html'

Any other suggestions would be great?

Swift post nested JSON object

I need to post the JSON object which is nested as below,

{
"params": {
    "City": "",
    "Country": "",
    "Email_Id": "abc@gmail.com",
    "MobileNumber": "1234",
    "UserName": "abc"
},
"userId": 0,
"userAddress": ""
}

How can I create an array or dictionary and pass it to NSURLRequest.

Class is not supported for deserialization of an array

I get an error:

System.InvalidOperationException: Type 'VK.Response' is not supported for deserialization of an array.

JSON that i get looks like:

{"response":[{"id":269058571,"first_name":"Name","last_name":"LastName","photo_50":"http://ift.tt/1JxM05L"}]}

My method is:

 private void getFriendInfo()
    {
        string method = "users.get";
        string param = "user_ids=269058571&fields=photo_50";
        string url = "http://ift.tt/1huYTUH" + method + "?" + param + "&v=5.31&access_token=" + key + "";

        WebClient client = new WebClient();

        string json = client.DownloadString(url);
        JavaScriptSerializer json_serializer = new JavaScriptSerializer();
        RootObject response = (RootObject)json_serializer.Deserialize(json, typeof(RootObject));
        for (int counter = 0; counter < response.response.items.Count; counter++)
        {
            pictureBox1.Load(response.response.items[counter].photo_50);
        }
    }

Classes:

      class Response
        {
            public int count { get; set; }
            public List<Item> items { get; set; }
        }

       class RootObject
       {
            public Response response { get; set; }
       }
       class Item
       {
            public string first_name { get; set; }
            public string last_name { get; set; }
            public string domain { get; set; }
            public string photo_50 { get; set; }
       }

Spring MVC server receiving json

I have created a spring mvc server. When I try sending JSON: { "shipName": "test", "signal": "test", "latitude": 12, "longitude": 12, "maxSpeed": 14 } to my web service I get: HTTP Status 400 - Required String parameter 'shipName' is not present.

Here's my server code:

@Controller
public class SignalController {

    @RequestMapping(value = "/signals", method = RequestMethod.GET)
    public @ResponseBody
    List<Signal> getAllSignals() throws SQLException,
            ClassNotFoundException {
        ISignalModel signalModel = new SignalModel();
        return signalModel.getSignals();
    }

    @RequestMapping(value = "/add", 
            method = RequestMethod.POST)
            @ResponseBody
                public void addSignal(@RequestBody Signal signal) {
        System.out.println("Signal");;
}

    @RequestMapping(value = "/addSignal", method = RequestMethod.POST)
    public ResponseEntity<Signal> add(
            @RequestBody Signal signal) throws SQLException,
            ClassNotFoundException {
        System.out.println(signal.getMaxSpeed());
        return new ResponseEntity<Signal>(signal, HttpStatus.OK);

    }

     @RequestMapping(value = "/addSignal2", method = RequestMethod.PUT)
public ResponseEntity<Signal> update(
        @RequestParam("shipName") String shipName,
        @RequestParam("signal") String signal,
        @RequestParam("latitude") int latitude,
        @RequestParam("longitude") int longitude,
        @RequestParam("maxSpeed") int maxSpeed
        ) throws SQLException,
        ClassNotFoundException {

    ISignalModel signalModel = new SignalModel();
    boolean operation = signalModel.addSignal(new Signal(shipName, signal,latitude, longitude, maxSpeed));

    if (operation) {
        return new ResponseEntity<Signal>(HttpStatus.OK);
    } else {
        return new ResponseEntity<Signal>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

Here's my signal class code:

public class Signal implements Serializable{

String ShipName;
String Signal;
//szerekość geograficzna
int Latitude; 
//długość geograficzna
int Longitude;
int MaxSpeed;



public Signal(String shipName, String signal, int latitude, int longitude,
        int maxSpeed) {
    super();
    ShipName = shipName;
    Signal = signal;
    Latitude = latitude;
    Longitude = longitude;
    MaxSpeed = maxSpeed;
}

//setters and getters

Asymmetric serialization and deserialization using Jackson

I am using Jackson to serialize and deserialize data for a RESTful API. I'd like to have a REST resource (/comments) that allows to POST comments as well as to GET a list of comments.

Here's a (simplified) example of what gets posted to /comments.

{"text":"Text","author":"Paul","email":"paul@example.org"}

Here's what the result of GET /comments should look like:

[{"text":"Text","author":"Paul","emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

Since email addresses shouldn't be visible to anyone, I decided to return only a MD5 hash of the email addresses in the response.

I have created a simple POJO class Comment that has fields with getters and setters for text, author, email, and emailHash.

Now, when I serialize the result, what I get is the following:

[{"text":"Text","author":"Paul","email":null,"emailHash":"76w0kjKP9HpsdhBjx895Sg=="}]

But I really don't like email to be returned as null here. It rather shouldn't be included at all.

Using the annotation @JsonIgnore on that field will also ignore it on deserialization. Do I have to create two classes, say CreationComment and ResultComment with a super-class Comment that shares common fields or is there a way that avoids creating additional classes?

Deserializing objects with gson, Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

i'm working on deserialization of feed coming from server. I have encountered a weird issue with Gson library. I'm using code i've found here on stack on similar issue thread, but it doesn't work.

Unfortunately i don't know where the problem is... Can someone point me in the right direction?

public static ArrayList<FeedItem> parseFeed(String toParse){
        Type collectionType = new TypeToken<Collection<FeedItem>>(){}.getType();
        ArrayList<FeedItem> outcome = new Gson().fromJson(toParse, collectionType);
        return outcome;
    }

Error

05-09 10:16:02.908    2385-2385/com.lanceit.haito.lanceit E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.lanceit.haito.lanceit, PID: 2385
    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
            at com.google.gson.Gson.fromJson(Gson.java:815)
            at com.google.gson.Gson.fromJson(Gson.java:768)
            at com.google.gson.Gson.fromJson(Gson.java:717)
            at com.lanceit.haito.lanceit.utils.SerializationHelper.parseFeed(SerializationHelper.java:25)
            at com.lanceit.haito.lanceit.network.lanceHandler.ListAllLances$1.onResponse(ListAllLances.java:30)
            at com.lanceit.haito.lanceit.network.lanceHandler.ListAllLances$1.onResponse(ListAllLances.java:27)
            at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
            at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:338)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
            at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
            at com.google.gson.Gson.fromJson(Gson.java:803)
            at com.google.gson.Gson.fromJson(Gson.java:768)
            at com.google.gson.Gson.fromJson(Gson.java:717)
            at com.lanceit.haito.lanceit.utils.SerializationHelper.parseFeed(SerializationHelper.java:25)
            at com.lanceit.haito.lanceit.network.lanceHandler.ListAllLances$1.onResponse(ListAllLances.java:30)
            at com.lanceit.haito.lanceit.network.lanceHandler.ListAllLances$1.onResponse(ListAllLances.java:27)
            at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
            at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)

How does marking classes as [Serializable] work in C#?

I made a class called MyData and marked it with [Serializable], but it doesn't seem to work...

Here's MyData.cs:

namespace Forms_Bot_Rebuild
{
    [Serializable]
    public class MyData
    {
        private String _Email;
        private String _Password;
        private String _WorldId;
        public MyData(string email, string password, string worldid)
        {
            _Email = email;
            _Password = password;
            _WorldId = worldid;
        }
        public string Email
        { get { return _Email; } set { _Email = value; } }
        public string Password
        { get { return _Password; } set { _Password = value; } }
        public string WorldId
        { get { return _WorldId; } set { _WorldId = value; } }
    }
}

Here's Form1.cs:

private void button1_Click(object sender, EventArgs e)
{
    MyData data = new MyData(boxEmail.Text, boxPass.Text, boxWorldId.Text);
    string objectNode = Serialize.ToJsonString(data);
    File.WriteAllText(Application.StartupPath + @"\LoginData.json", objectNode);
}
private void button2_Click(object sender, EventArgs e)
{   
    object myData;
    myData = Serialize.Deserialize<MyData>(new FileStream(Application.StartupPath + @"\LoginData.json", FileMode.Open));
    boxEmail.Text = data.Email;
    boxPass.Text = data.Password;
    boxWorldId.Text = data.WorldId;
}

Here's Serialize.cs:

public class Serialize
{
    public static StreamReader ToStreamReader(object o)
    {
        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
        ser.WriteObject(stream, o);
        stream.Position = 0;
        StreamReader sr = new StreamReader(stream);
        return sr;
    }
    public static string ToJsonString(object o)
    {
        MemoryStream stream = new MemoryStream();
        DataContractJsonSerializer ser = new DataContractJsonSerializer(o.GetType());
        ser.WriteObject(stream, o);
        stream.Position = 0;
        StreamReader sr = new StreamReader(stream);
        return sr.ReadToEnd();
    }
    public static object Deserialize<T>(Stream stream)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
        stream.Position = 0;
        T t = (T)ser.ReadObject(stream);
        return t;
    }
}

Also, this code was given to me by a friend, so I asked him. He couldn't understand it too. I asked another friend, who, in my opinion, knew decent C#, but he couldn't fix it too.

An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in System.Runtime.Serialization.dll

Additional information: Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

Any opinions?

Remove null elements from array jquery

I have my html like

  <input  type="text" class="form-control PaperSupply">` 
  <input  type="text" class="form-control PaperSupply">`
 <input  type="text" class="form-control PaperConsum">
 <input  type="text" class="form-control PC">

multiple inputs for same value papersupply and PaperConsum, in javascript i am creating an array for same value using map function like this

 var paperSupply = $('.PaperSupply').map(function(){return $(this).val();}).get(); 
 var PaperConsum= $('.PaperConsum').map(function(){return $(this).val();}).get(); 

now in json i want if any element of these array is null remove that element from array.

for example:

{"paperSupply":["","2","3","","5"],"paperConsum":["1","","4","5","6"]}

if this is json from above code, then i want above json like this,

{"paperSupply":["2","3","5"],"paperConsum":["","4","6"]}

Google Maps json output for all routes

my question is about google maps json output. i've here a start address and end address :

Google Maps Link

And at the following link, i display the result as json format :

Google Maps Json Format

It displays only one legs(route), but from start address to end address i've 4 routes. My question is, how can i display all routes in my json output?

Can you help me? Thanks in advance.

Staggered Gridview ( Etsy ) with Volley Network Image View

I would like to implement Etsy's Staggered Gridview. Problem is, that i don't know how to combine Volley's NetworkImage View with this. I get the Imageurl from a Json file, for that i'm using volley.

Here is my MainActivity.class

import com.etsy.android.grid.StaggeredGridView;


 public class NeuImKino extends ActionBarActivity {    
 private Toolbar toolbar;



// Log tag
private static final String TAG = MainActivity.class.getSimpleName();

// Movies json url
private static final String url =     "http://***json";

private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private static String Title = "title";
private static String movie = "movie";
private static StaggeredGridView mGridView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_neu_im_kino);
    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);

    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawerLayout), toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    mGridView = (StaggeredGridView) findViewById(R.id.grid_view);
    //listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    //listView.setAdapter(adapter);
    mGridView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();


    // JSON PARSING
    JsonObjectRequest movieReq = new JsonObjectRequest(url,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();
                    parseJSONResponse(response);

                }
            }, new Response.ErrorListener()

    {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();

        }
    }

    );

    // Adding request to request queue
    AppController.getInstance().

            addToRequestQueue(movieReq);


    /**listView.setOnItemClickListener(new AdapterView.OnItemClickListener()

                                    {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                            String name = ((TextView) view.findViewById(R.id.title)).getText().toString();
                                            Intent intent = new Intent(NeuImKino.this, SingleItemView.class);

                                            intent.putExtra(Title, name);

                                            startActivity(intent);
                                        }
                                    }

    ); **/
}


public void parseJSONResponse(JSONObject response) {
    try {
        if (response.has("movie")) {
            JSONArray arrayMovies = response.getJSONArray("movie");
            for (int i = 0; i < arrayMovies.length(); i++) {
                JSONObject currentMovie = arrayMovies.getJSONObject(i);
                Movie movie = new Movie();

                String title = null;
                if (currentMovie.has("title")) {
                    title = currentMovie.getString("title");
                } else {
                    title = "NA";
                }

                String fsk;
                if (currentMovie.has("fsk")) {
                    fsk = currentMovie.getString("fsk");
                } else {
                    fsk = "NA";
                }
                String country = null;
                if (currentMovie.has("country")) {
                    country = currentMovie.getString("country");
                } else {
                    country = "NA";
                }


                String start = null;
                if (currentMovie.has("start")) {
                    start = currentMovie.getString("start");
                } else {
                    start = "NA";
                }

                String longdesc = null;
                if (currentMovie.has("longdesc")) {
                    longdesc = currentMovie.getString("longdesc");
                } else {
                    longdesc = "NA";
                }

                String imgname = null;
                if (currentMovie.has("imgname")) {
                    imgname = currentMovie.getString("imgname");
                } else {
                    imgname = null;
                }
                movie.setTitle(title);
                movie.setFsk(fsk);
                movie.setStart(start);
                movie.setCountry(country);
                movie.setLongDesc(longdesc);
                movie.setImgName(imgname);
                movieList.add(movie);


            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    adapter.notifyDataSetChanged();


}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

}

My CustomListAdapter:

public class CustomListAdapter extends BaseAdapter {
private static String CONFIG_URL = "http://****";
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();



// Constructor
public CustomListAdapter(Activity activity, List<Movie> movieItem) {
    this.activity = activity;
    this.movieItems = movieItems;

}

@Override
public int getCount() {
    return movieItems.size();
}

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

// Create each list view row
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        // Layout Inflater to call external xml layout
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        // Inflate list_row_neuimkino file for each row
        convertView = inflater.inflate(R.layout.list_row_neuimkino, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();


    DynamicHeightImageView poster = (DynamicHeightImageView) convertView.findViewById(R.id.image);
    //TextView title = (TextView) convertView.findViewById(R.id.title);
    //TextView fsk = (TextView) convertView.findViewById(R.id.fsk);
    //TextView start = (TextView) convertView.findViewById(R.id.start);


    // getting movie data for the row from Model object
    Movie m = movieItems.get(position);
 // Set Model Values in Holder Items
    // thumbnail image

    //poster.setImageUrl(CONFIG_URL+m.getImgName()+"_w300.jpg", imageLoader);


    // title
   // title.setText(m.getTitle());

    // fsk
    //fsk.setText("FSK: " + m.getFsk());

    // Startdatum
    //start.setText("Beginnt: " +m.getStart());


    return convertView;
}

}

And finally my layoutfile for one row

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<com.etsy.android.grid.util.DynamicHeightImageView
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center" />

Pull json data and assign to global variable [duplicate]

This question already has an answer here:

I am pulling data from a JSON file using $.getJson. This data is assigned to the variables gameType, host, and port. Then another $.getjson makes a request using the data pulled from the first json file. The JSON data being requested in the FOR Loop is data being queried from source game servers.

See this link for an example of the data received from a query

The FOR loop is to iterate over the multiple servers that need to be queried. I am trying to take all the data that is received from all the queries that are made, and assign it to a my array "now". I believe the problem is my misunderstanding of the scope, but i'm not too sure. Thanks for any insight you can give me.

var now = Array();
                    $.getJSON("http://ift.tt/1Rngi0D", function(response, $scope) {
                        var arr = response.servers;


                        for(var i = 0; i < arr.length; i++) {
                            var gameType = arr[i].gametype;
                            var servHost = arr[i].host;
                            var servPort = arr[i].port;

                            $.getJSON("http://ift.tt/1PwDUMt"+gameType+"&host="+servHost+"&port="+servPort, function(data, $scope) {
                                var html = "";
                                html += "<tr>";
                                html += "<td>" + data.game_dir + "</td>";
                                html += "<td>" + data.hostname + "</td>";
                                html += "<td>" + data.gq_address + ":" + data.gq_port + "</td>";
                                html += "<td>" + data.map + "</td>";
                                html += "<td>" + data.num_players + "/" + data.max_players + "</td>";

                                html += "</tr>";
                                now[i]=data;
                                $("#server-data tbody").append(html);

                            });
                        }

                        console.log(now);
                    });

Spray-Json - How to define field constraints

I have case class which represents my json model:

case class UserData(photo_url: String, age: Int, bio: String)

and wondering how could I define some constraints on some specific fields, like length for bio or value range for age?

pikaday angular sending date format in json

how do i send the pikaday plugin date format in my json using ng-model

i had been trying this

<input pikaday="" ng-model="products_chosen[$index].from.getDate()" placeholder="From">

js:

    $scope.products_chosen = [{"from":new Date(),"till":new Date(),"checkbox":0}];
    $scope.productChange = function(index, checkbox){
        if(checkbox==1){
            $scope.products_chosen.push({"from":"","till":"","checkbox":0});  
        }
        else{
            $scope.products_chosen.splice(index,1);
        } 
    }

Is this json wrong?

I've created the following json:

{ "posts" : [
    {"post" : 
        {"person" : somePerson,
        "messages" : [person says : Hello how are you,person2 says : I'm fine]
        }
    },
    {"post" : 
        {"person" : someOtherPerson,
        "messages" : [person says : I'm happy,person2 says : me too]
        }
    }
  ] 
}

But jquery .done is not being called with this input. I suspect there is something wrong with the format of the json. I don't know if I'm allowed to pass an aaray "messages" inside a json object. If I'm not, how can I resolve this? Thanks in advance.

Issues with Alamofire Request in Swift using Xcode 6.3.1

Could someone help this newbie with a question. I have created the following class

import Foundation

class Search {

var firstName: String
var lastName: String
var dob: String


init(firstName: String, lastName: String, dob: String)
{

    self.firstName = firstName
    self.lastName = lastName
    self.dob = dob
}

}

I have then imported Alamofire into my swift project as i want to make a json request to a rest web service.

This is my request

let searchParameters = Search(firstName: "frankie", lastName: "jones",dob: "09-08-1995")

    request(.GET, "http://blahblahblah/get", parameters: searchParameters)
       .response { (request, response, data, error) in
            println(request)
            println(response)
            println(error) 

So why am I getting the following error: Cannot invoke 'response' with an argument list of type ((,,_))->)'??

Any Ideas? Thx

Unable to pass result of a query to view and render into JSON

I am trying to query a Parse table and I am able to get the data out. I am then passing that data to a Parse View to be rendered into a handlebar template. The view in itself is working when I manually input JSON data into the collection variable.

My problem is that the data is not getting passed to the View from the query or not getting converted to JSON. I keep getting the following error:

Uncaught TypeError: this.collection.toJSON is not a function

// render template with context data 
var StoresView =  Parse.View.extend({
template: Handlebars.compile($('#storetable-tpl').html()),
render: function(){ 
    var collection = { storeList: this.collection.toJSON() };
    this.$el.html(this.template(collection));
}
});

// query the store table data
allStores.equalTo("shape","Round");
allStores.limit(10);
allStores.descending("updatedAt");
allStores.find({
success: function(results) {
    var storesView = new StoresView({ collection: results });
    storesView.render();
    $('#stores-table').html(storesView.el);
} 
});  

What am I doing wrong?

How can I store multiple values in json?

pretty simple question.

I am trying to learn polymer and have made a survey. For one of the questions I would like to assign multiple values as the answer but for some reason I can only get it working with one value.

"survey": [

        {
            "type": "picker",
            "question": "Please rate out of 5",
            "min": 1,
            "max": 5,
            "answer": 5
        }, 

This returns a positive result when the user selects 5 but when the user selects 1-4 it is incorrect.

What I would like to do is store multiple values in the 'answer' field so that if the user selects 1-5 they all register as correct.

How can I do this? I have tried

[1, 2, 3, 4, 5]

and it still doesn't work.

Reading multiple Responses from server

I'm using C# and via a webapi I need to send a request to a server and process the response. The data that comes back from the server has the form like:

{"A_Field":a,"B_Field":"B_FieldValue","C_Field":5}

{"TYPE":"Values","Column1":["1234","456789","12345"],"Column2":["abc","defg","high"]}
{"TYPE":"Values","Column1":["45353","23422","6755"],"Column2":["sfs","fhfghg","vzczzc"]}
{"TYPE":"Values","Column1":["4564","5664","12345"],"Column2":["abfsdc","vxvx","cxvbvx"]}
{"TYPE":"Values","Column1":["5664","979","7978"],"Column2":["ryrt","qweq","nbmm"]}

....

{"A_Field":b,"COMPLETE:"YES"}

I need to process the parts that start with {"TYPE":"Values"....} There are an exceptionally large amount of these messages that are returned from the server. So to be able to process each line/message as it is received would be ideal. The last line that has "COMPLETE:"YES"} signals the end of the message. I tried the below code:

try{
    using (var handler = new HttpClientHandler())
    {
         handler.Credentials = new System.Net.NetworkCredential("user", "password");
         using (var client = new HttpClient(handler))
         {
            client.BaseAddress = new Uri("http://<server>:port/api/rest/");
            await client.GetAsync(blah_query)
              .ContinueWith(taskwithresponse =>
                HttpResponseMessage response = taskwithresponse.Result;
          }
     }
  }
 catch(Exception e)
 {
    Console.WriteLine("Error {0}",e.Message);
 }

The output gives: Error: One or more errors occurred

This fails when the response is very large. I'm guessing that processing has to be done in the loop? But I believe what is happening here is that it's waiting for the entire message to return. Or is this the completely wrong way to go about it.

I'm not familiar with web programming. But can someone help advise on how I can process the returned data in an optimal way? Is it possible to do it a line/message at a time? A code sample/tutorial would be a great help. Most of what i've seen uses a small amount of data.

Calling JSON and data retrieval working in browser but not in Cordova emulator or mobile

I am building a mobile web app using html5, there I am fetching the data from my WCF rest serice. Problem is it's working fine in browser, when converted in to app using Apache Cordova it's not working.

I'm getting http_request.readyState :4 and http_request.status :0 instead of 200. I thought it's a problem with cross domain issue so used ajax instead of Java function and enabled CORS in web.config of WCF still problem persists

Can anyone help out please?

Thanks in advance

Vikram

PS : when using ajax function its getting into error function but displaying a error message success:200, don't what it means

$.ajax({
                dataType: 'jsonp',
                type: "GET",
                url: "http://dev_test_srv/RestServiceImpl.svc/json/123?callback=?",
                success: function (data) {
                    alert(123);
                    alert("working");
                },
                error: function (error) {
                    alert(error.statusText + "-" + error.status);
                }
});

var data_file = "http://dev_test_srv/RestServiceImpl.svc/Employees/" + id + "/" + pwd;
alert(data_file);

var http_request = new XMLHttpRequest();

try {
                // Opera 8.0+, Firefox, Chrome, Safari
                http_request = new XMLHttpRequest();
} catch (e) {
                // Internet Explorer Browsers
                try {
                    http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
                    try {
                        http_request = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        // Something went wrong
                        alert("Your browser broke!");
                        return false;
                    }
                }
}

http_request.onreadystatechange = function () {
                alert(http_request.readyState + '--' + http_request.status);
                if (http_request.readyState == 4 && http_request.status == 200) {
                    var stringouptut = http_request.responseText;
                    var replacedstring = stringouptut.replace(/\\/g, "");
                    var newresult = "{ \"Data\": " + replacedstring.substring(replacedstring.indexOf("["));
                    var final = newresult.substring(0, newresult.length - 2) + " " + " }";

                    final = JSON.parse(final);

                    if (final.Data.length > 0) {

                        if (final.Data[0].status == "Valid") {

                            localStorage.UserId = id;

                            window.location = "doctors.html";
                        }
                        else {
                            document.getElementById("lblerror").innerHTML = "Invalid Employee ID/Password";
                        }

                    }
                }
            }
            http_request.open("GET", data_file, true);
            http_request.send();

Config settings in web.config :

<httpProtocol>
    <customHeaders> 
         <add name="Access-Control-Allow-Origin" value="*"/>
         <add name="Access-Control-Allow-Headers" value="Content-Type, Accept"/>
         <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />                             <add name="Access-Control-Max-Age" value="1728000" />
    </customHeaders> 
</httpProtocol>

vendredi 8 mai 2015

Trouble accessing data multiple objects in JSON with Python

I am trying to parse through a web-service and retrieve certain records, however I am consistently receiving a KeyError for responses with more than one object. These records are returned in intervals, so sometimes I might receive one record and others I might receive 300. If I receive one record, the logic of my code works, if there are multiple items then the code doesn't work.

Here is an example of an output with one object.

{
    "status": {
        "code": 311,
        "message": "Service Request Successfully Queried.",
        "cause": ""
    },
    "Response": {
        "NumOutputObjects": "1",
        "ListOfServiceRequest": {
            "ServiceRequest": [
                {
                    "AddressVerified": "Y",
                    "SRNumber": "1-13967451",
                    "SRType": "Service Not Complete",
                    "CreatedDate": "05/08/2015 10:00:38",
                    "UpdatedDate": "05/08/2015 10:00:49",
                    "IntegrationId": "05082015100148678",
                    "Status": "Open",
                    "CreatedByUserLogin": "PROXYE",
                    "UpdatedByUserLogin": "PROXYE",
                    "Anonymous": "N",
                    "Zipcode": "90032",
                    "Latitude": "34.0843242531",
                    "Longitude": "-118.171015007",
                    "CustomerAccessNumber": "",
                    "LADWPAccountNo": "",
                    "NewContactFirstName": "jj",
                    "NewContactLastName": "rambo",
                    "NewContactPhone": "",
                    "NewContactEmail": "",
                    "ParentSRNumber": "1-10552271",
                    "Priority": "Normal",
                    "Language": "",
                    "ReasonCode": "",
                    "ServiceDate": "",
                    "Source": "",
                    "ClosedDate": "",
                    "Email": "",
                    "FirstName": "",
                    "HomePhone": "",
                    "LastName": "",
                    "LoginUser": "",
                    "ResolutionCode": "",
                    "SRUnitNumber": "",
                    "MobilOS": "",
                    "SRAddress": "5163 E TEMPLETON ST, 90032",
                    "SRAddressName": "",
                    "SRAreaPlanningCommission": "East Los Angeles APC",
                    "SRCommunityPoliceStation": "CENTRAL BUREAU",
                    "SRCouncilDistrictMember": "Jose Huizar",
                    "SRCouncilDistrictNo": "14",
                    "SRDirection": "E",
                    "SRNeighborhoodCouncilId": "48",
                    "SRNeighborhoodCouncilName": "LA-32 NC",
                    "SRStreetName": "TEMPLETON",
                    "SRSuffix": "ST",
                    "SRTBColumn": "F",
                    "SRTBMapGridPage": "595",
                    "SRTBRow": "6",
                    "SRXCoordinate": "6509897",
                    "SRYCoordinate": "1853117",
                    "AssignTo": "NC",
                    "Assignee": "NC eWaste Supervisor 01",
                    "Owner": "BOS",
                    "ParentSRStatus": "Open",
                    "ParentSRType": "Electronic Waste",
                    "ParentSRLinkDate": "05/08/2015 10:00:39",
                    "ParentSRLinkUser": "PROXYE",
                    "SRAreaPlanningCommissionId": "5",
                    "SRCommunityPoliceStationAPREC": "HOLLENBECK",
                    "SRCommunityPoliceStationPREC": "4",
                    "SRCrossStreet": "",
                    "ActionTaken": "",
                    "SRCity": "",
                    "RescheduleCounter": "",
                    "SRHouseNumber": "5163",
                    "SourceofRequestCouncil": "",
                    "CCBPremiseType": "",
                    "ContainerBlackCount": "",
                    "ContainerBrownCount": "",
                    "SRIntersectionDirection": "",
                    "SRApproximateAddress": "N",
                    "ContainerGreenCount": "",
                    "OtherBureauName": "",
                    "AssigneeName": "",
                    "AssigneeOrganization": "E-Waste, NC",
                    "AnotherBureauEmailId": "",
                    "ListOfLa311BarricadeRemoval": {},
                    "ListOfLa311BulkyItem": {},
                    "ListOfLa311DeadAnimalRemoval": {},
                    "ListOfLa311GraffitiRemoval": {},
                    "ListOfLa311InformationOnly": {},
                    "ListOfLa311MultipleStreetlightIssue": {},
                    "ListOfLa311SingleStreetlightIssue": {},
                    "ListOfLa311SrPhotoId": {
                        "La311SrPhotoId": []
                    },
                    "ListOfLa311BusPadLanding": {},
                    "ListOfLa311CurbRepair": {},
                    "ListOfLa311Flooding": {},
                    "ListOfLa311GeneralStreetInspection": {},
                    "ListOfLa311GuardWarningRailMaintenance": {},
                    "ListOfLa311GutterRepair": {},
                    "ListOfLa311LandMudSlide": {},
                    "ListOfLa311Pothole": {},
                    "ListOfLa311Resurfacing": {},
                    "ListOfLa311SidewalkRepair": {},
                    "ListOfLa311StreetSweeping": {},
                    "ListOfLa311BeesOrBeehive": {},
                    "ListOfLa311MedianIslandMaintenance": {},
                    "ListOfLa311OvergrownVegetationPlants": {},
                    "ListOfLa311PalmFrondsDown": {},
                    "ListOfLa311StreetTreeInspection": {},
                    "ListOfLa311StreetTreeViolations": {},
                    "ListOfLa311TreeEmergency": {},
                    "ListOfLa311TreeObstruction": {},
                    "ListOfLa311TreePermits": {},
                    "ListOfLa311BrushItemsPickup": {},
                    "ListOfLa311Containers": {},
                    "ListOfLa311ElectronicWaste": {},
                    "ListOfLa311IllegalDumpingPickup": {},
                    "ListOfLa311ManualPickup": {},
                    "ListOfLa311MetalHouseholdAppliancesPickup": {},
                    "ListOfLa311MoveInMoveOut": {},
                    "ListOfLa311HomelessEncampment": {},
                    "ListOfLa311IllegalAutoRepair": {},
                    "ListOfLa311IllegalConstruction": {},
                    "ListOfLa311IllegalConstructionFence": {},
                    "ListOfLa311IllegalDischargeOfWater": {},
                    "ListOfLa311IllegalDumpingInProgress": {},
                    "ListOfLa311IllegalExcavation": {},
                    "ListOfLa311IllegalSignRemoval": {},
                    "ListOfLa311IllegalVending": {},
                    "ListOfLa311LeafBlowerViolation": {},
                    "ListOfLa311NewsRackViolation": {},
                    "ListOfLa311Obstructions": {},
                    "ListOfLa311TablesAndChairsObstructing": {},
                    "ListOfLa311GisLayer": {
                        "La311GisLayer": [
                            {
                                "A_Call_No": "",
                                "Area": "0",
                                "Day": "MONDAY",
                                "DirectionSuffix": "",
                                "DistrictAbbr": "",
                                "DistrictName": "NC",
                                "DistrictNumber": "",
                                "DistrictOffice": "",
                                "Fraction": "",
                                "R_Call_No": "",
                                "SectionId": "",
                                "ShortDay": "",
                                "StreetFrom": "",
                                "StreetTo": "",
                                "StreetLightId": "",
                                "StreetLightStatus": "",
                                "Type": "GIS",
                                "Y_Call_No": "",
                                "Name": "05082015100148678100",
                                "CommunityPlanningArea": "",
                                "LastUpdatedBy": "",
                                "BOSRadioHolderName": ""
                            }
                        ]
                    },
                    "ListOfLa311ServiceRequestNotes": {
                        "La311ServiceRequestNotes": [
                            {
                                "CreatedDate": "05/08/2015 10:00:39",
                                "Comment": "Materials have been out in a normal collection area, unsure why driver missed the e-waste items.",
                                "CreatedByUser": "PROXYE",
                                "IsSrNoAvailable": "",
                                "CommentType": "External",
                                "Notification": "N",
                                "FeedbackSRType": "",
                                "IntegrationId": "050820151001486782",
                                "Date1": "",
                                "Date2": "",
                                "Date3": "",
                                "Text1": "",
                                "AnotherBureau": "",
                                "EmailAddress": "",
                                "ListOfLa311SrNotesAuditTrail": {}
                            },
                            {
                                "CreatedDate": "05/08/2015 10:00:39",
                                "Comment": "",
                                "CreatedByUser": "PROXYE",
                                "IsSrNoAvailable": "",
                                "CommentType": "Address Comments",
                                "Notification": "N",
                                "FeedbackSRType": "",
                                "IntegrationId": "050820151001486781",
                                "Date1": "",
                                "Date2": "",
                                "Date3": "",
                                "Text1": "",
                                "AnotherBureau": "",
                                "EmailAddress": "",
                                "ListOfLa311SrNotesAuditTrail": {}
                            }
                        ]
                    },
                    "ListOfLa311SubscribeDuplicateSr": {},
                    "ListOfChildServiceRequest": {},
                    "ListOfLa311BillingCsscAdjustment": {},
                    "ListOfLa311BillingEccAdjustment": {},
                    "ListOfLa311BillingRsscAdjustment": {},
                    "ListOfLa311BillingRsscExemption": {},
                    "ListOfLa311SanitationBillingBif": {},
                    "ListOfLa311SanitationBillingCssc": {},
                    "ListOfLa311SanitationBillingEcc": {},
                    "ListOfLa311SanitationBillingLifeline": {},
                    "ListOfLa311SanitationBillingRssc": {},
                    "ListOfLa311SanitationBillingSrf": {},
                    "ListOfLa311DocumentLog": {},
                    "ListOfAuditTrailItem2": {
                        "AuditTrailItem2": [
                            {
                                "Date": "05/08/2015 10:00:49",
                                "EmployeeLogin": "SADMIN",
                                "Field": "Assignee",
                                "NewValue": "NC eWaste Supervisor 01",
                                "OldValue": ""
                            }
                        ]
                    },
                    "ListOfLa311GenericBc": {
                        "La311GenericBc": [
                            {
                                "ATTRIB_08": "",
                                "NAME": "05082015100148678100",
                                "PAR_ROW_ID": "1-8BDCR",
                                "ROW_ID": "1-8BOCG",
                                "TYPE": "GIS",
                                "ATTRIB_16": "",
                                "ListOfLa311GenericbcAuditTrail": {}
                            },
                            {
                                "ATTRIB_08": "",
                                "NAME": "05082015100148678",
                                "PAR_ROW_ID": "1-8BDCR",
                                "ROW_ID": "1-8BOCJ",
                                "TYPE": "Service Not Complete",
                                "ATTRIB_16": "",
                                "ListOfLa311GenericbcAuditTrail": {}
                            }
                        ]
                    },
                    "ListOfLa311ServiceNotComplete": {
                        "La311ServiceNotComplete": [
                            {
                                "ContainerLocation": "",
                                "ContainerType": "",
                                "DriverFirstName": "",
                                "DriverLastName": "",
                                "MissedCollectionService": "Electronic Waste",
                                "OtherServiceMissedReason": "",
                                "ServiceDateRendered": "",
                                "ServiceMissedReason": "I'm not sure",
                                "TruckNo": "",
                                "Type": "Service Not Complete",
                                "WireBasketLocation": "",
                                "LastUpdatedBy": "",
                                "Name": "05082015100148678"
                            }
                        ]
                    },
                    "ListOfLa311Other": {},
                    "ListOfLa311WeedAbatementForPrivateParcels": {},
                    "ListOfLa311SanitationBillingInquiry": {}
                }
            ]
        }
    }
}

The code is below;

data2 = jsonpickle.decode((f2.read()))
Start = datetime.datetime.now()
data2 = jsonpickle.encode(data2)
url2 = "myURL"
headers2 = {'Content-type': 'text/plain', 'Accept': '/'}

r2 = requests.post(url2, data=data2, headers=headers2)
decoded2 = json.loads(r2.text)
try:
    r2
except requests.exceptions.ConnectTimeout as e:
    print "Too slow Mojo!"


items = []
for sr in decoded2['Response']['ListOfServiceRequest']['ServiceRequest']:
    SRAddress = sr['SRAddress']
    Latitude = sr['Latitude']
    Longitude = sr['Longitude']
    ReasonCode = sr['ReasonCode']
    SRNumber = sr['SRNumber']
    FirstName = sr['FirstName']
    LastName = sr['LastName']
    ResolutionCode = sr['ResolutionCode']
    HomePhone = sr['HomePhone']
    CreatedDate = sr['CreatedDate']
    UpdatedDate = sr['UpdatedDate']
    CreatedDate = datetime.datetime.strptime(CreatedDate, "%m/%d/%Y %H:%M:%S")
    UpdatedDate = datetime.datetime.strptime(UpdatedDate, "%m/%d/%Y %H:%M:%S")
    print SRAddress
    print SRNumber


ItemInfo = " "
for ew in sr["ListOfLa311ServiceRequestNotes"][u"La311ServiceRequestNotes"]:
Comment = ew['Comment']
print Comment

Output Materials have been out in a normal collection area, unsure why driver missed the e-waste items.

If I use the logic above for a response with more than one object returned I receive a KeyError value and am unable to access the array that I want to parse.

Example of code with multiple objects returned;

Output when I use; I receive a key error if I attempt to do something along the lines of CommodityType = sr['ListOfLa311ElectronicWaste']['ElectronicWasteType'] below

for sr in decoded2['Response']['ListOfServiceRequest']['ServiceRequest']:
        CommodityType = sr['ListOfLa311ElectronicWaste']
        # ItemType = sr['ElectronicWestType']
        # DriverFirstName = sr ['DriverFirstName']
        # DriverLastName = sr ['DriverLastName']
        # ItemCount = sr['ItemCount']
        # ItemInfo += '{0},  {1}, '.format(ItemType, ItemCount)
        # ParentNumber = sr['Name']
        #
        print CommodityType




{u'La311ElectronicWaste': [{u'IllegallyDumped': u'N', u'OtherElectronicWestType': u'hash', u'ItemCount': u'5', u'Name': u'6a31f058-ece1-4e7d-b682-7d9052a512f4', u'MobileHomeSpace': u'', u'DriverLastName': u'', u'ActiveStatus': u'Y', u'DriverFirstName': u'', u'LastUpdatedBy': u'', u'GatedCommunityMultifamilyDwelling': u'Outside the main gate', u'IllegalDumpCollectionLoc': u'', u'ElectronicWestType': u'Other', u'CollectionLocation': u'Gated Community', u'Type': u'Electronic Waste', u'ServiceDateRendered': u'', u'TruckNo': u''}]}
{u'La311ElectronicWaste': [{u'IllegallyDumped': u'Y', u'OtherElectronicWestType': u'', u'ItemCount': u'5', u'Name': u'3f4d9d20-a712-4be3-822f-e6a45219c1cf', u'MobileHomeSpace': u'', u'DriverLastName': u'', u'ActiveStatus': u'Y', u'DriverFirstName': u'', u'LastUpdatedBy': u'', u'GatedCommunityMultifamilyDwelling': u'', u'IllegalDumpCollectionLoc': u'Cul De Sac', u'ElectronicWestType': u'Electronic Equipment', u'CollectionLocation': u'Alley', u'Type': u'Electronic Waste', u'ServiceDateRendered': u'', u'TruckNo': u''}]}

How do I handle multiple outputs the same way that I have handled the single output?

Parsing JSON data from Yelp API

I'm new to programming and am trying to parse some data returned from Yelp's API. From this data, how could I return something like just the phone number (display_phone) and address? Thank you

Result for business "little-miss-bbq-phoenix-2" found:
{ u'categories': [[u'Barbeque', u'bbq']],
  u'display_phone': u'+1-602-437-1177',
  u'id': u'little-miss-bbq-phoenix-2',
  u'image_url': u'http://ift.tt/1DXoWIP',
  u'is_claimed': True,
  u'is_closed': False,
  u'location': { u'address': [u'4301 E University Dr'],
                 u'city': u'Phoenix',
                 u'coordinate': { u'latitude': 33.421587,
                                  u'longitude': -111.989088},
                 u'country_code': u'US',
                 u'display_address': [ u'4301 E University Dr',
                                       u'Phoenix, AZ 85034'],
                 u'geo_accuracy': 9.5,
                 u'postal_code': u'85034',
                 u'state_code': u'AZ'},
  u'mobile_url': u'http://ift.tt/1JVI9CL',
  u'name': u'Little Miss BBQ',
  u'phone': u'6024371177',
  u'rating': 5.0,
  u'rating_img_url': u'http://ift.tt/WVmntb',
  u'rating_img_url_large': u'http://ift.tt/WVmntd',
  u'rating_img_url_small': u'http://ift.tt/1o2fewz',
  u'review_count': 403,
  u'reviews': [ { u'excerpt': u"I saw that this place had almost 400 reviews and that they have a perfect 5 star rating. It sounded too good to be true BUT it's worth every star and...",
                  u'id': u'-9poa0ycpVnOveVlqbYE9Q',
                  u'rating': 5,
                  u'rating_image_large_url': u'http://ift.tt/WVmntd',
                  u'rating_image_small_url': u'http://ift.tt/1o2fewz',
                  u'rating_image_url': u'http://ift.tt/WVmntb',
                  u'time_created': 1431095420,
                  u'user': { u'id': u'd43iQ50HjWIl4vN4rBgoVQ',
                             u'image_url': u'http://ift.tt/1JVI8yX',
                             u'name': u'Jason J.'}}],
  u'snippet_image_url': u'http://ift.tt/1JVI8yX',
  u'snippet_text': u"I saw that this place had almost 400 reviews and that they have a perfect 5 star rating. It sounded too good to be true BUT it's worth every star and...",
  u'url': u'http://ift.tt/1IobOkA'}