Affichage des articles dont le libellé est Active questions tagged json - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged json - Stack Overflow. Afficher tous les articles

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)