Rectangle 27 1

Don't convert the response to json. It's already json.

Replace the following line:

json = JSON.parse(response.to_json, symbolize_names: true)
json = JSON.parse(response, symbolize_names: true)
to_s

@, forgot the response is string-like object. removed the to_s. Thank you for the feedback.

response according to the documentation it is an object but github.com/rest-client/rest-client#usage-raw-url response.body return a string I'am little bit confused. But your answer is right.

@, According to github.com/rest-client/rest-client#result-handling, New in 2.0: RestClient::Response objects are now a subclass of String. Previously, they were a real String object with response functionality mixed in, which was very confusing to work with.

Ruby on sinatra, JSON::parserError issue and 757: unexpected token - S...

json ruby parsing hash sinatra
Rectangle 27 8

Your JSON is invalid. You've said you can't change it, which is unfortunate.

It looks like it's been double-stringified but then the outermost quotes have been left off. If so, you can fix it by adding " at each end and then double-parsing it, like this:

var str = '{\\"value1\\":\\"XYZ\\",\\"value2\\":\\"ZYX\\"}';
str = '"' + str + '"';
var obj = JSON.parse(JSON.parse(str));
console.log(obj);

Ideally, though, you'll want to go through the database and correct the invalid data.

I actually thought double escape was the correct way of escaping in string/JSON.

In JSON, strings are wrapped in double quotes ("), not double escapes. You only escape double quotes within strings (with a single \).

If you've been creating JSON strings manually (in code), don't. :-) Instead, create the structure you want to save, and then stringify it. Building JSON strings manually is error-prone, but a proper JSON stringifier will be reliable.

I initially thought of cutting the backslahes away using a regex, but your solution is way better. So I cancelled writing my own answer, and can only say: upvote :-)

javascript - SyntaxError: Unexpected token \ in JSON at position - Sta...

javascript json node.js
Rectangle 27 4

Just use " instead of ' in your json:

var test = JSON.parse('{"0": [{"text": "conquistar", "value": 1559.0}, {"text": "mujer", "value": 1559.0}, {"text": "no", "value": 866.0}, {"text": "olvidar", "value": 842.0}, {"text": "libros", "value": 842.0}, {"text": "ltimos", "value": 645.0}, {"text": "imdb", "value": 645.0}, {"text": "aos", "value": 645.0}, {"text": "encontrars", "value": 519.0}, {"text": "donde", "value": 519.0}, {"text": "pginas", "value": 519.0}, {"text": "tatuaje", "value": 519.0}, {"text": "sabas", "value": 481.0}, {"text": "potter", "value": 481.0}, {"text": "universo", "value": 481.0}, {"text": "harry", "value": 481.0}, {"text": "del", "value": 481.0}, {"text": "datos", "value": 481.0}, {"text": "cmo", "value": 388.0}, {"text": "n", "value": 353.0}, {"text": "netflix", "value": 256.0}, {"text": "deberas", "value": 256.0}, {"text": "bicicleta", "value": 255.0}, {"text": "amo", "value": 255.0}, {"text": "mi", "value": 255.0}, {"text": "incestuosas", "value": 242.0}, {"text": "julio", "value": 242.0}, {"text": "cortzar", "value": 242.0}, {"text": "relaciones", "value": 242.0}, {"text": "decir", "value": 236.0}, {"text": "frases", "value": 236.0}, {"text": "adis", "value": 236.0}, {"text": "poder", "value": 215.0}, {"text": "mundo", "value": 215.0}, {"text": "anorexia", "value": 215.0}, {"text": "moda", "value": 215.0}, {"text": "los", "value": 202.0}, {"text": "a", "value": 167.0}, {"text": "like", "value": 147.0}, {"text": "ves", "value": 147.0}, {"text": "esto", "value": 147.0}, {"text": "facebook", "value": 147.0}, {"text": "das", "value": 147.0}, {"text": "prximo", "value": 129.0}, {"text": "segn", "value": 128.0}, {"text": "nico", "value": 127.0}, {"text": "edificio", "value": 127.0}, {"text": "construido", "value": 127.0}, {"text": "cartas", "value": 127.0}, {"text": "si", "value": 126.0}, {"text": "psicpata", "value": 108.0}, {"text": "eres", "value": 108.0}, {"text": "definir", "value": 108.0}, {"text": "tus", "value": 108.0}, {"text": "gustos", "value": 108.0}, {"text": "podran", "value": 108.0}, {"text": "mexicanos", "value": 105.0}, {"text": "conocer", "value": 105.0}, {"text": "debes", "value": 105.0}, {"text": "ilustradores", "value": 105.0}, {"text": "cerebro", "value": 96.0}, {"text": "porno", "value": 96.0}, {"text": "afecta", "value": 96.0}, {"text": "nunca", "value": 91.0}, {"text": "pelculas", "value": 89.0}, {"text": "qu", "value": 82.0}, {"text": "opcin", "value": 80.0}, {"text": "negro", "value": 80.0}, {"text": "vestir", "value": 80.0}, {"text": "mejores", "value": 78.0}, {"text": "de", "value": 67.0}, {"text": "por", "value": 65.0}, {"text": "amor", "value": 64.0}, {"text": "en", "value": 64.0}, {"text": "directores", "value": 63.0}, {"text": "cine", "value": 63.0}, {"text": "nuevos", "value": 63.0}, {"text": "terror", "value": 63.0}, {"text": "para", "value": 61.0}, {"text": "le", "value": 61.0}, {"text": "pasa", "value": 61.0}, {"text": "lo", "value": 61.0}, {"text": "la", "value": 59.0}, {"text": "las", "value": 58.0}, {"text": "un", "value": 56.0}, {"text": "el", "value": 56.0}, {"text": "mejor", "value": 47.0}, {"text": "baile", "value": 45.0}, {"text": "ertico", "value": 45.0}, {"text": "que", "value": 42.0}, {"text": "elvie", "value": 40.0}, {"text": "videojuego", "value": 40.0}, {"text": "exclusivo", "value": 40.0}, {"text": "vagina", "value": 40.0}, {"text": "ver", "value": 39.0}, {"text": "una", "value": 39.0}, {"text": "tu", "value": 39.0}, {"text": "canciones", "value": 38.0}, {"text": "dije", "value": 32.0}, {"text": "versos", "value": 32.0}, {"text": "tengo", "value": 32.0}, {"text": "te", "value": 32.0}, {"text": "siempre", "value": 32.0}, {"text": "fiesta", "value": 32.0}, {"text": "pena", "value": 32.0}, {"text": "pero", "value": 32.0}, {"text": "dan", "value": 32.0}, {"text": "bailas", "value": 32.0}, {"text": "ganar", "value": 32.0}, {"text": "dicaprio", "value": 32.0}, {"text": "oscar", "value": 32.0}, {"text": "todo", "value": 30.0}, {"text": "inspir", "value": 29.0}, {"text": "bohemia", "value": 29.0}, {"text": "diseadora", "value": 29.0}, {"text": "klimt", "value": 29.0}, {"text": "gustav", "value": 29.0}, {"text": "ests", "value": 27.0}, {"text": "soar", "value": 27.0}, {"text": "seal", "value": 27.0}, {"text": "pblico", "value": 27.0}, {"text": "desnudo", "value": 27.0}, {"text": "consumes", "value": 25.0}, {"text": "rostro", "value": 25.0}, {"text": "droga", "value": 25.0}, {"text": "fotografas", "value": 25.0}, {"text": "con", "value": 17.0}, {"text": "es", "value": 13.0}, {"text": "hacer", "value": 10.0}, {"text": "tatuajes", "value": 9.0}, {"text": "wars", "value": 9.0}, {"text": "star", "value": 9.0}, {"text": "inspirados", "value": 9.0}, {"text": "razones", "value": 9.0}, {"text": "vida", "value": 8.0}, {"text": "zombies", "value": 6.0}, {"text": "novelas", "value": 6.0}, {"text": "amante", "value": 6.0}, {"text": "marciales", "value": 6.0}, {"text": "tiene", "value": 6.0}, {"text": "artes", "value": 6.0}, {"text": "trip", "value": 2.0}, {"text": "road", "value": 2.0}, {"text": "perdonar", "value": 1.0}, {"text": "posible", "value": 1.0}, {"text": "infidelidad", "value": 1.0}]}');

console.log(test);

More information in JSON specification json.org

javascript - SyntaxError: Unexpected token ' in JSON at position 1 - S...

javascript json
Rectangle 27 3

Might as well just make an array if the output expected has arrays.

But who needs loops when you have map?

var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');

console.log(array1.map((s, idx) => [s,array2[idx]]));

He doesn't want a JSON string, he just wants an array.

javascript - Unexpected token at JSON position - Stack Overflow

javascript json
Rectangle 27 2

You could simply loop over the first array, and then push a single array onto your output array.

var string1 = "BODEBO,CARNE";
var array1 = string1.split(',');
var string2 = "1,2";
var array2 = string2.split(',');

var a = [];

for(var i=0;i<array1.length;i++){
    a.push([ array1[i], array2[i] ]);
}

// You can now just make use of the 'a' array.
console.log(a);

Giving you the following output: [["BODEBO","1"],["CARNE","2"]]

He doesn't want a JSON string, he just wants an array.

@Stephan Thanks for pointing this out, I've updated my code and explained the results in comments.

javascript - Unexpected token at JSON position - Stack Overflow

javascript json
Rectangle 27 2

app.post('/books',function (req, res) {
 Book.create(req.body)
   .then(function (createdBook) {
       //On success return a created object
       return res.json(createdBook);
    })
   .catch(function (err) {
      //On error return error
      return res.json(err);
    });
  });
});

Use method create to save object in db. Can you show us object wich you want to save?

IARKI An explanation would be nice. btw im still getting the same error.

node.js - Unexpected token d in JSON at position 6 - Stack Overflow

json node.js mongodb mongoose
Rectangle 27 2

app.post('/books',function (req, res) {
 Book.create(req.body)
   .then(function (createdBook) {
       //On success return a created object
       return res.json(createdBook);
    })
   .catch(function (err) {
      //On error return error
      return res.json(err);
    });
  });
});

Use method create to save object in db. Can you show us object wich you want to save?

IARKI An explanation would be nice. btw im still getting the same error.

node.js - Unexpected token d in JSON at position 6 - Stack Overflow

json node.js mongodb mongoose
Rectangle 27 1

ECMA-404 The JSON Data Interchange Standard says:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes

In your case you have single quoutes

str.replace("'", """);

javascript - SyntaxError: Unexpected token ' in JSON at position 1 - S...

javascript json
Rectangle 27 1

For your second question Not necessarily. You should check both in your server and your front-end configuration that you are actually allowed to receive plain text as a response.

The official $http documentation will help you about setting your header correctly, while I let you check for your server configuration as well.

Is "test" a valid route ? It seems that $http tries to get "test" as a plain text, and not the resource which is stored behind "test", as the firt incorrect character is 't'. Otherwise (if it is a valid route), please refer on the above-mentioned answer.

When calling $http (even in localhost), you must mention the full route to your resource. Here, you cannot directly call ("test"), it interprets it as a plain "test" request. Try calling:

$http.get('localhost:[your port]/test').then { ...what you need to do... });

text/plain and plain/text makes a difference when configuringn, be careful ! This fixed the asker's problem.

sorry, but did not get how to fix the issue. /test is returning "test" as output, with Content/type as plain/text. How to resolve the error?

Try accessing your server with the following syntax: $http.get('localhost:[your port]/test'). I think this should solve the problem.

As someone downvoted me I cannot comment your question anymore, but I'll do it here. If you are getting the same error (angular.js:13550 SyntaxError: Unexpected token t in JSON at position 1 at Object.parse (native)) and your server sends plain/text, it means that your AngularJS application expects JSON. As I linked you before, I advise you reading this page which covers effectively headers and content type (official documentation).

By the way, as I also read through, try text/plain instead of plain/text

javascript - SyntaxError: Unexpected token e in JSON at position 1 - S...

javascript angularjs ajax
Rectangle 27 1

First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.

All the phases where you can do so, in chronological order:

<Files "confirm3.php">
    ForceType application/json
</Files>
  • Report data type from PHP: header('Content-Type: application/json');
  • Tell jQuery that you expect JSON: url: "confirm3.php", method: "POST", dataType: "json", data: { Submit: "true" }, success: function(response) { console.log(data); // Already decoded (don't use alert to debug!) }

You can certainly omit almost any step, but not all.

Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.

javascript - Uncaught SyntaxError: Unexpected token in JSON at positio...

javascript php jquery json ajax
Rectangle 27 1

You should check the response from the server using the network tab and append it to your question. Looks like your JSON-Response is corrupt. This often happens when an error message is printed before the output is sent or when nothing is sent.

Angular 2 - Unexpected token < in JSON at position 0 - WebAPI [HttpPos...

json angular asp.net-web-api http-post angular2-services
Rectangle 27 1

it seems you are using a custom input widget, which uploads to a different url (/uploads). you didn't show the code for this specific /uploads action. need more information.

btw, "<" in JSON looks like you are returning HTML instead of json. maybe you are throwing an exception. check it in your runtime/logs.

you are still hiding your controller action for handling uploads specified in 'uploadUrl' => Url::to(['/site/file-upload']),

upload - Error uploading image in yii2(SyntaxError: Unexpected token <...

image upload yii2
Rectangle 27 1

First of all, jQuery can decode JSON automatically for you (and it will make its best to guess). Trying to do it manually only makes your code more verbose and error-prone. However, you don't give it any hint. Nothing in the code you've shared gives any clue about your intention to use jQuery.

All the phases where you can do so, in chronological order:

<Files "confirm3.php">
    ForceType application/json
</Files>
  • Report data type from PHP: header('Content-Type: application/json');
  • Tell jQuery that you expect JSON: url: "confirm3.php", method: "POST", dataType: "json", data: { Submit: "true" }, success: function(response) { console.log(data); // Already decoded (don't use alert to debug!) }

You can certainly omit almost any step, but not all.

Secondly, if you get a JSON parse error the very first you need to check is whether the response is valid JSON. The most straightforward way to see it is using the browser developer tools, more specifically the "Network" pane.

javascript - Uncaught SyntaxError: Unexpected token in JSON at positio...

javascript php jquery json ajax
Rectangle 27 1

Instead of having response in text/ html format you can ask for JSON data

Simply add one more attribute DataType: JSON in your ajax call and send response in JSON format using json_encode() from PHP

$.ajax({
  type:"POST",
  url:"test.php",
  data:{data:'data'},
  dataType: 'json',
  success: function(data){
    if(data['success']=='true'){
        alert('success');
    }else{
      if(data['success']=='false'){
        alert("not success");
      }
    }
  }
});
if($_POST['data']==1){
      $response['success'] = "true";
   } else {
      $response['success'] = "false";
   }

echo json_encode($response);
<?php 		 	if(isset($_POST['yearID']) && isset($_POST['districtID'])) 	{ 		$year=$_POST['yearID']; 		$district=$_POST['districtID'];  		$checkdata=" SELECT year, district FROM indicators WHERE year='$year' and district='$district' ";  		$query=$conn->query($checkdata);  		if($year=$query->fetch_assoc()) 		{ 			echo json_encode($year);	   		}	 		else 		{ 			echo 'false'; 		} 		exit(); 	} ?>

if(isset($_POST['yearID']) && isset($_POST['districtID'])) { $response = array(); $year=$_POST['yearID']; $district=$_POST['districtID']; $checkdata=" SELECT year, district FROM indicators WHERE year='$year' and district='$district' "; $query=$conn->query($checkdata); if($year=$query->fetch_assoc()) { $response['success'] = "true"; $response['year'] = $year; } else { $response['success'] = "false"; } echo json_encode($response); exit(); } ?>

<?Php @$div_code=$_GET['div_code'];  if(!is_numeric($div_code)){ echo "Data Error"; exit;  }    $sql="select dis_name, dis_id from t_hdms_code_district where dis_div_id='$div_code'"; $row=$dbo->prepare($sql); $row->execute(); $result=$row->fetchAll(PDO::FETCH_ASSOC);  $main = array('data'=>$result); echo json_encode($main); ?>

Data error seems is from dd.php from the console tracking.

javascript - Uncaught SyntaxError: Unexpected token D in JSON at posit...

javascript php mysql json
Rectangle 27 1

My guess would be is that you redirect all your requests to index.html or that you are receiving a custom 404 page. Try going to http://localhost:53796/api/CarAuction in your browser and check the response.

Unexpected token < in JSON

This almost always refer to a html page trying to be parsed to JSON. The response image you post, is not the response you get from the server. You should check the network tab for that.

Angular 2 - Unexpected token < in JSON at position 0 - WebAPI [HttpPos...

json angular asp.net-web-api http-post angular2-services
Rectangle 27 0

I saw some weird log entries on my own site [which doesn't use Ruby] and Google took me to this thread. The IP on my entries was different. [120.37.236.161]

First, in my own logs I saw a reference to http://api.alihack.com/info.txt - checked this link out; looked like an attempt at a PHP injection.

There's also a "register.php" page there - submitting takes you to an "invite.php" page.

Further examination of this domain took me to http://www.alihack.com/2014/07/10/168.aspx (page is in Chinese but Google Translate helped me out here)

I expect this "Black Spider" tool has been modified by script kiddies and is being used as a carpet bomber to attempt to find any sites which are "vulnerable."

It might be prudent to just add an automatic denial of any attempt including the "alihack" substring to your configuration.

<%eval request(\"alihack.com\")%>

"It might be prudent to just add an automatic denial of any attempt including the "alihack" substring to your configuration." This is almost certainly a terrible idea. See, e.g., the Scunthorpe problem.

hey @JohnFeminella! nice bumping into you :) I totally agree it's a bad idea. I'm curious about your thoughts / opinion about the possible alternatives I suggested on my answer.

ruby on rails - (JSON::ParserError) "{N}: unexpected token at 'alihack...

ruby-on-rails ruby json ruby-on-rails-3
Rectangle 27 0

No, it's not. It has something to do with the way the js is escaped, because not building it through a partial (directly in the js file) has worked, but with some manual escaping.

have you tried <%= escape_javascript(render(@download)) %> ?

Rails ajax/partial not rendering properly - Stack Overflow

ajax ruby-on-rails-3
Rectangle 27 0

In my case it was a hidden tab character which showed up only when i pasted it into vim.

The same in my case. Had some whitespace around the object

Ruby on Rails JSON.parse unexpected token error - Stack Overflow

json ruby-on-rails-3
Rectangle 27 0

What you have is a hash printed as String. To convert it into a Hash use eval.

ch = "{\"report_name\"=>\"Study/Control: ABIRATERONE ACETATE - 20151413355\", \"left_mue_start_date\"=>\"02-26-2015\", \"left_mue_end_date\"=>\"03-19-2015\", \"right_mue_start_date\"=>\"02-26-2015\", \"right_mue_end_date\"=>\"03-19-2015\", \"report_formulary_id\"=>\",7581\", \"mue\"=>\"true\", \"mue_type\"=>\"study/control\", \"chain_id\"=>\"1\", \"left_mue_formulary_ids\"=>[\"7581\"], \"action\"=>\"create_report\", \"controller\"=>\"informatics\", \"user_id\"=>339}"
hash = eval(ch)
# => {"report_name"=>"Study/Control: ABIRATERONE ACETATE - 20151413355", "left_mue_start_date"=>"02-26-2015", "left_mue_end_date"=>"03-19-2015", "right_mue_start_date"=>"02-26-2015", "right_mue_end_date"=>"03-19-2015", "report_formulary_id"=>",7581", "mue"=>"true", "mue_type"=>"study/control", "chain_id"=>"1", "left_mue_formulary_ids"=>["7581"], "action"=>"create_report", "controller"=>"informatics", "user_id"=>339}

PS: A JSON string should look as follows, meaning what you have is not JSON and hence you got JSON::ParserError for using JSON.parse on a non-JSON string :

"{\"report_name\":\"Study/Control: ABIRATERONE ACETATE - 20151413355\",\"left_mue_start_date\":\"02-26-2015\",\"left_mue_end_date\":\"03-19-2015\",\"right_mue_start_date\":\"02-26-2015\",\"right_mue_end_date\":\"03-19-2015\",\"report_formulary_id\":\",7581\",\"mue\":\"true\",\"mue_type\":\"study/control\",\"chain_id\":\"1\",\"left_mue_formulary_ids\":[\"7581\"],\"action\":\"create_report\",\"controller\":\"informatics\",\"user_id\":339}"

Just be careful using eval because it can inject malicious code inside you system depending upon where your hash come from

eval

ruby on rails - JSON::ParserError: 757: unexpected token at '{ - Stack...

ruby-on-rails ruby json
Rectangle 27 0

the Me. comes from code in a Userform.

Option Explicit
Public Const gACCESS_TOKEN As String = "xxxxxxxxxxxxxxxxxxxxxx"
Declare Function GetTickCount Lib "kernel32" () As Long
Declare Sub Sleep Lib "kernel32" (ByVal lngMilliSeconds As Long)
' for a JSON parser see https://code.google.com/p/vba-json/

Public Sub test()
Dim vRequestBody  As Variant, sResponse As String, sSurveyID As String
sSurveyID = "1234567890"

vRequestBody = "{""survey_id"":" & """" & sSurveyID & """" _
              & ", ""fields"":[""collector_id"", ""url"", ""open"", ""type"", ""name"", ""date_created"", ""date_modified""]" _
              & "}"
sResponse = SMAPIRequest("get_collector_list", vRequestBody)

End Sub
Function SMAPIRequest(sRequest As String, vRequestBody As Variant) As String
Const SM_API_URI As String = "https://api.surveymonkey.net/v2/surveys/"
Const SM_API_KEY As String = "yyyyyyyyyyyyyyyyyyyyyyyy"
Dim bDone As Boolean, sMsg As String, sUrl As String, oHttp As Object ' object MSXML2.XMLHTTP
Static lsTickCount As Long

If Len(gACCESS_TOKEN) = 0 Then
   Err.Raise 9999, "No Access token"
End If
On Error GoTo OnError

sUrl = SM_API_URI & URLEncode(sRequest) & "?api_key=" & SM_API_KEY
   'Debug.Print Now() & " " & sUrl
Application.StatusBar = Now() & " " & sRequest & " " & Left$(vRequestBody, 127)
Set oHttp = CreateObject("MSXML2.XMLHTTP") ' or "MSXML2.ServerXMLHTTP"

Do While Not bDone ' 4.33 offer retry
   If GetTickCount() - lsTickCount < 1000 Then ' if less than 1 sec since last call, throttle to avoid sResponse = "<h1>Developer Over Qps</h1>"
      Sleep 1000 ' wait 1 second so we don't exceed limit of 2 qps (queries per second)
   End If
   lsTickCount = GetTickCount()
   'Status  Retrieves the HTTP status code of the request.
   'statusText Retrieves the friendly HTTP status of the request.
   'Note   The timeout property has a default value of 0.
   'If the time-out period expires, the responseText property will be null.
   'You should set a time-out value that is slightly longer than the expected response time of the request.
   'The timeout property may be set only in the time interval between a call to the open method and the first call to the send method.
RetryPost:  ' need to do all these to retry, can't just retry .Send apparently
   oHttp.Open "POST", sUrl, False   ' False=not async
   oHttp.setRequestHeader "Authorization", "bearer " & gACCESS_TOKEN
   oHttp.setRequestHeader "Content-Type", "application/json"

   oHttp.send CVar(vRequestBody)     ' request body needs brackets EVEN around Variant type
   '-2146697211   The system cannot locate the resource specified. => no Internet connection
   '-2147024809   The parameter is incorrect.
   'String would return {"status": 3, "errmsg": "No oJson object could be decoded: line 1 column 0 (char 0)"} ??
   'A Workaround would be to use parentheses oHttp.send (str)
   '"GET" err  -2147024891   Access is denied.
   '"POST" Unspecified error = needs URLEncode body? it works with it but

   SMAPIRequest = oHttp.ResponseText
   'Debug.Print Now() & " " & Len(SMAPIRequest) & " bytes returned"
   sMsg = Len(SMAPIRequest) & " bytes returned in " & (GetTickCount() - lsTickCount) / 1000 & " seconds: " & sRequest & " " & Left$(vRequestBody, 127)

   If Len(SMAPIRequest) = 0 Then
      bDone = MsgBox("No data returned - do you wish to retry?" _
            & vbLf & sMsg, vbYesNo, "Retry?") = vbNo
   Else
      bDone = True ' got reply.
   End If
Loop ' Until bdone

   Set oHttp = Nothing
   GoTo ExitProc

OnError:   ' Pass True to ask the user what to do, False to raise to caller
   Select Case MsgBox(Err.Description, vbYesNoCancel, "SMAPIRequest")
   Case vbYes

      Resume RetryPost
   Case vbRetry
      Resume RetryPost
   Case vbNo, vbIgnore
      Resume Next
   Case vbAbort
      End
   Case Else
      Resume ExitProc ' vbCancel
   End Select
ExitProc:
End Function


Public Function URLEncode(StringVal As String, Optional SpaceAsPlus As Boolean = False) As String
Dim StringLen As Long
 StringLen = Len(StringVal)
 If StringLen > 0 Then
   ReDim result(StringLen) As String
   Dim i As Long, CharCode As Integer
   Dim Char As String, Space As String
   If SpaceAsPlus Then Space = "+" Else Space = "%20"
   For i = 1 To StringLen
      Char = Mid$(StringVal, i, 1)
      CharCode = Asc(Char)
      Select Case CharCode
      Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
      result(i) = Char
      Case 32
      result(i) = Space
      Case 0 To 15
      result(i) = "%0" & Hex(CharCode)
      Case Else
      result(i) = "%" & Hex(CharCode)
      End Select
   Next i
   URLEncode = Join(result, "")
End If
End Function
Set jLib = New JSONLib
vRequestBody = "{"
If Me.txtDaysCreated > "" Then
   vRequestBody = vRequestBody & JKeyValue("start_date", Format$(Now() - CDbl(Me.txtDaysCreated), "yyyy-mm-dd")) & ","
End If
If Me.txtTitleContains > "" Then
' title contains "text", case insensitive
vRequestBody = vRequestBody & JKeyValue("title", Me.txtTitleContains) & ","
End If
vRequestBody = vRequestBody _
   & JKeyValue("fields", Array("title", "date_created", "date_modified", "num_responses", _
      "language_id", "question_count", "preview_url", "analysis_url")) & "}"


'returns in this order: 0=date_modified  1=title  2=num_responses  3=date_created   4=survey_id
' and in date_created descending
sResponse = GetSMAPIResponse("get_survey_list", vRequestBody)

------------------------------------------
Function JKeyValue(sKey As String, vValues As Variant) As String
      Dim jLib As New JSONLib
 JKeyValue = jLib.toString(sKey) & ":" & jLib.toString(vValues)
 Set jLib = Nothing
End Function

This is covered in the SM documentation, but I'll sketch how that looks in VBA. the response to get_survey_details gives you all the survey setup data. Use Set oJson = jLib.parse(Replace(sResponse, "\r\n", " ")) to get a json object. Set dictSurvey = oJson("data") gives you the dictionary so you can get data like dictSurvey("num_responses"). I take it you know how to index into dictionary objects to get field values.

Set collPages = dictSurvey("pages")

gives you a collection of Pages. The undocumented field "position" gives you the order of pages in the survey UI.

For lPage = 1 To collPages.Count
   Set dictPage = collPages(lPage) 
Set collPageQuestions = dictPage("questions") ' gets you the Qs on this page
For lPageQuestion = 1 To collPageQuestions.Count
     Set dictQuestion = collPageQuestions(lPageQuestion) ' gets you one Q
Set collAnswers = dictQuestion("answers") ' gets the QuestionOptions for this Q
        For lAnswer = 1 To collAnswers.Count
           Set dictAnswer = collAnswers(lAnswer) ' gets you one Question Option

Then given the number of responses from above, loop through the respondents 100 at a time - again see the SM doc for details of how to specify start and end dates to do incremental downloads over time. create a json object from the response to "get_respondent_list" Collect the fields for each respondent and accumulate a list of at most 100 respondent IDs. Then "get_responses" for that list.

Set collResponsesData = oJson("data")
For lResponse = 1 To collResponsesData.Count

If not IsNull(collResponsesData(lResponse)) then 
... get fields...
Set collQuestionsAnswered = collResponsesData(lResponse)("questions")
  For lQuestion = 1 To collQuestionsAnswered.Count
     Set dictQuestion = collQuestionsAnswered(lQuestion)
        nQuestion_ID = CDbl(dictQuestion("question_id"))
        Set collAnswers = dictQuestion("answers") ' this is a collection of dictionaries
        For lAnswer = 1 To collAnswers.Count

           On Error Resume Next ' only some of these may be present
           nRow = 0: nRow = CDbl(collAnswers(lAnswer)("row"))
           nCol = 0: nCol = CDbl(collAnswers(lAnswer)("col"))
           nCol_choice = 0: nCol_choice = CDbl(collAnswers(lAnswer)("col_choice"))
           sText = "": sText = collAnswers(lAnswer)("text")
           nValue = 0: nValue = Val(sText)  
           On Error GoTo 0

and save all those values in a recordset or sheet or whatever Hope that helps.

Thanks @sysmod I really appreciate your help. I will have a look at this. Give me a few more hours to digest this and I will come back to you! I thought that putting a @ in front of your "name" in the comments will alert you of replies etc.?

You have made my day, @sysmod! I have it working now! Even for a basic get_survey_list call. Though it seems a bit complicated building the vRequestBody string! This will be trickier than I thought. will JSON help in building the vRequestBody string too? Or is this just for "unpacking" the response I get back?

No, I don't get an email alert from Stackoverflow after posts. Is there some box I should have checked "alert me when someone replies" ? I use the .toString function in the JSONlib to form the body. eg Function JKeyValue(sKey As String, vValues As Variant) As String Dim jLib As New JSONLib JKeyValue = jLib.toString(sKey) & ":" & jLib.toString(vValues) Set jLib = Nothing End Function I need more space to reply, and cannot format comments as code, so I;ll add another answer.

You'll need to patch the JSONlib - the owner may have done this too since I found it: in function ParseString change this: Case """", "\", "/" ' POB fix issue 22 in lib And in parseNumber: parseNumber = CDbl(Value) ' POB always Double, not Int, need not be decimal point in long number eg 623478675 and in sub skipChar While Index > 0 And Index <= Len(str) And InStr(vbCr & vbLf & vbTab & " ", Mid(str, Index, 1)) ' POB don't need vbCrLf as well

I searched Help and found that hovering over the [surveymonkey] tag gives a popup with a 'subscribe' link to notify me of new posts with that tag. I'll try that.

excel vba - Accessing SurveyMonkey API from VBA - Stack Overflow

excel-vba surveymonkey