I have a JSON String being parsed (in a response var) from AJAX:  The JSON  {    "TheArray":[         {            "AlmostThere": {               "whatWeAreLookingFor":"Hello"          }       },       {         "AlmostThere": {             "whatWeAreLookingFor":"Goodbye"         }       }    ] }   The JSON being parsed  var jsonData = JSON.parse(response); //response is the string version of the JSON code!   Now, I need to loop into the JSON array, hereby mentioned as TheArray. I do this:  Looping TheArray  for (var contents in jsonData["TheArray"]) {  }   And inside there, we get the value of the whatWeAreLookingFor element:  for (var contents in jsonData["TheArray"]) {     console.log(contents.whatWeAreLookingFor + "!"); }   But there is a catch! The console outputs... undefined!. -  I have tried multiple ways to make this work, such as using contents["whatWeAreLookingFor"] and what-not, but I still get the same results.
5927
I've been told not to use for...in with arrays in JavaScript. Why not?
13251
Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?  Let's say we have an array of associative arrays:  var myArray = [{'key': 'value'}, {'key': 'value1'}];   So we can iterate:  for (var i = 0; i &lt; myArray.length; i++)   And:  for (var i in myArray)   I don't see a big difference. Are there any performance issues?
34916
I have an issue which I've been struggling with today. The JSON is returned back to me with a project Id as the key, this Project Id is dynamically generated and due to this I have not been able to come up with a way to deserialize this response. Any suggestions?   {      "success":true,    "numRows":5,    "data":{         "23000079":{            "projectId":"23000079",          "name":"Mcdonalds",          "departmentId":"9383",          "responsibleUserId":"7444434"       }    } }
7837
Is DOM the only way to parse JSON?
54783
Is there any way to deserialize JSON into an object using JSON.deserialize if some of the property names in the JSON are reserved words in apex? I want to do something like this:  string jsonString = '{"currency" : "ABC"}'; public class JSONResult {     public string currency; } JSONResult res = (JSONResult) JSON.deserialize(jsonString, JSONResult.class); system.debug(res);   but of course I get an error that the identifier name is reserved.
14405
Trends data from Twitter Search API in JSON.  Grabbing the file using:  $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json);   How do I work with data from this object. As an array? Only really need to extract data from the [name] values.  JSON object contains:  stdClass Object (     [trends] =&gt; Array         (             [0] =&gt; stdClass Object                 (                     [name] =&gt; Vote                     [url] =&gt; http://search.twitter.com/search?q=Vote                 )              [1] =&gt; stdClass Object                 (                     [name] =&gt; Halloween                     [url] =&gt; http://search.twitter.com/search?q=Halloween                 )              [2] =&gt; stdClass Object                 (                     [name] =&gt; Starbucks                     [url] =&gt; http://search.twitter.com/search?q=Starbucks                 )              [3] =&gt; stdClass Object                 (                     [name] =&gt; #flylady                     [url] =&gt; http://search.twitter.com/search?q=%23flylady                 )              [4] =&gt; stdClass Object                 (                     [name] =&gt; #votereport                     [url] =&gt; http://search.twitter.com/search?q=%23votereport                 )              [5] =&gt; stdClass Object                 (                     [name] =&gt; Election Day                     [url] =&gt; http://search.twitter.com/search?q=%22Election+Day%22                 )              [6] =&gt; stdClass Object                 (                     [name] =&gt; #PubCon                     [url] =&gt; http://search.twitter.com/search?q=%23PubCon                 )              [7] =&gt; stdClass Object                 (                     [name] =&gt; #defrag08                     [url] =&gt; http://search.twitter.com/search?q=%23defrag08                 )              [8] =&gt; stdClass Object                 (                     [name] =&gt; Melbourne Cup                     [url] =&gt; http://search.twitter.com/search?q=%22Melbourne+Cup%22                 )              [9] =&gt; stdClass Object                 (                     [name] =&gt; Cheney                     [url] =&gt; http://search.twitter.com/search?q=Cheney                 )          )      [as_of] =&gt; Mon, 03 Nov 2008 21:49:36 +0000 )
64488
I am trying to parse url-encoded strings that are made up of key=value pairs separated by either &amp; or &amp;amp;.   The following will only match the first occurrence, breaking apart the keys and values into separate result elements:  var result = mystring.match(/(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/)   The results for the string '1111342=Adam%20Franco&amp;348572=Bob%20Jones' would be:  ['1111342', 'Adam%20Franco']   Using the global flag, 'g', will match all occurrences, but only return the fully matched sub-strings, not the separated keys and values:  var result = mystring.match(/(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/g)   The results for the string '1111342=Adam%20Franco&amp;348572=Bob%20Jones' would be:  ['1111342=Adam%20Franco', '&amp;348572=Bob%20Jones']   While I could split the string on &amp; and break apart each key/value pair individually, is there any way using JavaScript's regular expression support to match multiple occurrences of the pattern /(?:&amp;|&amp;amp;)?([^=]+)=([^&amp;]+)/ similar to PHP's preg_match_all() function?  I'm aiming for some way to get results with the sub-matches separated like:  [['1111342', '348572'], ['Adam%20Franco', 'Bob%20Jones']]   or   [['1111342', 'Adam%20Franco'], ['348572', 'Bob%20Jones']]
40928
How can you check whether a string is convertible to an int?  Let's say we have data like "House", "50", "Dog", "45.99", I want to know whether I should just use the string or use the parsed int value instead.  In JavaScript we had this  function. If the string couldn't be parsed, it would get back NaN.
80715
In javascript, what is the best way to parse an INT from a string which starts with a letter (such as "test[123]")?  I need something that will work for the example below.  My JS:  $(document).ready(function() {      $(':input').change( function() {         id = parseInt($(this).attr("id"));  //fails for the data below         alert(id);     }); }   My generated HTML:  &lt;select id="attribute[123]"&gt; &lt;!-- various options --&gt; &lt;/select&gt; &lt;select id="attribute[456]"&gt; &lt;!-- various options --&gt; &lt;/select&gt;   Thank you!
14806
How do I remove empty elements from an array in JavaScript?   Is there a straightforward way, or do I need to loop through it and remove them manually?
110820
I'm currently making a callout to a 3rd party vendor and I'm getting a huge response. What is currently messing me up is this section:   "MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false   As you can see here, the portion at the end of the Description value is ended with backslash double quote. If I attempt to parse this via the JSONParser I get an exception. Does anyone have an recommendations on how to resolve this?  Exception Message:  System.JSONException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [line:1, column:3699]  Updated with sample Code   public class ResponseWrapper{     // fields from JSON to auto map     public Integer messageSeq;     public String Description;     public String messageTS;     public Integer messageLevel;     public Boolean isSystemMessage;     // parsing fields     private ResponseWrapper theResponse;     private JSONParser parser;      public void parse(String jsonString){         parser = JSON.createParser(jsonString);         parseJSON();     }      private void parseJSON(){            while (parser.nextToken() != null) {             if (parser.getCurrentToken() == JSONToken.START_OBJECT) {                 theResponse = (ResponseWrapper)parser.readValueAs(ResponseWrapper.class);                            }         }     } }  String responseString = '{"MessageSeq":13,"Description":"config file: config-qa1.txt\"","MessageTS":"2014-02-17T14:46:58","MessageLevel":4,"IsSystemMessage":false}'; system.debug('\n\nBEFORE\n' + responseString); ****Place code in here to test such as ReplaceALL*** ResponseWrapper parser = new ResponseWrapper(); parser.parse(responseString);
17166
I have a list of integers, List&lt;Integer&gt; and I'd like to convert all the integer objects into Strings, thus finishing up with a new List&lt;String&gt;.  Naturally, I could create a new List&lt;String&gt; and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?
123088
I am writing a SQL query creator using some parameters. In Java, it's very easy to detect the last element of an array from inside the for loop by just checking the current array position with the array length.  for(int i=0; i&lt; arr.length;i++){      boolean isLastElem = i== (arr.length -1) ? true : false;         }   In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision (in my case to append or/and parameter while building query).   I am sure there must be some standard way of doing this.   How do you solve this in PHP?
109364
I have a method which takes params object[] such as:  void Foo(params object[] items) {     Console.WriteLine(items[0]); }   When I pass two object arrays to this method, it works fine:  Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[]   But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:  Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[]   How do I pass a single object[] as a first argument to a params array?
51639
I am using .Net framework 2.0 / jQuery to make an Ajax call to a 2.0 web service. No matter what I set the contentType to in the ajax call, the service always returns XML. I want it to return Json!  Here is the call:        $(document).ready(function() {          $.ajax({             type: "POST",             url: "DonationsService.asmx/GetDate",             data: "{}",             contentType: "application/json; charset=utf-8",             dataType: "json",             success: function(msg) {               // Hide the fake progress indicator graphic.               $('#RSSContent').removeClass('loading');                // Insert the returned HTML into the &lt;div&gt;.               $('#RSSContent').html(msg.d);             }           });         });       Here is what the request header looks like in Fiddler:  POST /DonationsService.asmx/GetDate HTTP/1.1 x-requested-with: XMLHttpRequest Accept-Language: en-us Referer: http://localhost:1238/text.htm Accept: application/json, text/javascript, */* Content-Type: application/json; charset=utf-8 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727) Host: localhost:1238 Content-Length: 2 Connection: Keep-Alive Pragma: no-cache   I have tried setting the contentType to 'text/json' and get the same results.  Here is the web service method:  &lt;WebMethod()&gt; _ Public Function GetDate() As String      'just playing around with Newtonsoft.Json     Dim sb As New StringBuilder     Dim sw As New IO.StringWriter(sb)     Dim strOut As String = String.Empty      Using jw As New JsonTextWriter(sw)         With jw             .WriteStartObject()             .WritePropertyName("DateTime")             .WriteValue(DateTime.Now.ToString)             .WriteEndObject()         End With         strOut = sw.ToString     End Using      Return strOut  End Function   and here is what it returns:  &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;string xmlns="http://DMS.Webservices.org/"&gt;{"DateTime":"11/13/2008 6:04:22 PM"}&lt;/string&gt;   Does anyone know how to force the web service to return Json when I ask for Json?  Please don't tell me to upgrade to .Net Framework 3.5 or anything like that (I'm not that stupid). I need a 2.0 solution.
115970
Using a ajax request I want to change content of my div.  &lt;div id="d1"&gt;202&lt;/div&gt;   So I want to change the content to a different number.  $('d1').InnerText???   Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
33695
I have a Java bean like this:  class Person {   int age;   String name; }   I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.  The code to generate the table rows will look something like this:  &lt;c:forEach var="person" items="${personList}"&gt;   &lt;tr&gt;&lt;td&gt;${person.name}&lt;td&gt;&lt;td&gt;${person.age}&lt;/td&gt;&lt;/tr&gt; &lt;/c:forEach&gt;   However, I'm struggling to find a way to calculate the age total that will be shown in the final row without resorting to scriptlet code, any suggestions?