We help IT Professionals succeed at work.

JSON

1K

Solutions

953

Contributors

JavaScript Object Notation, or JSON, is human-readable text used when transmitting data objects consisting of attribute:value pairs between a server and a web application as an alternative to XML. JSON, while it is originally derived from JavaScript, is a language-independent data format. Code for parsing and generating JSON data is available in many programming languages.

Can someone tell me if this is a valid json file? It is named transportation.json.
Basically it is three different arrays. Each array represents a form of transportation.

{
"cars":[ "Ford", "BMW", "Fiat" ]
}
{
"bicycles":[ "Scott", "Orbea", "Cannondale" ]
}
{
"skateboards":[ "Element", "Hikole", "Ztuntz" ]
}
0
JSON data parse
How can  make the following code extract the numeric value from the "meals" element

Need the numeric value from this:  "meals":55. which is contained in the return json from the following getJSON

code:
       $.getJSON("https://api.gsa.gov/travel/perdiem/v2/rates/city/Richland/state/WA/year/2019?api_key=8DYKMOjODhqMfQLD3t4xFsXVeav1LkIPX5aOihPK", function (data) {
             var items = [];
            $.each( data, function( key, val ) {
                  //items.push( "<li id='" + key + "'>" + val + "</li>" );
                  //alert(key + " "+ val);
            });            

sample return json (see meals:55 below:
{"request":null,"errors":null,"rates":[{"oconusInfo":null,"rate":[{"months":{"month":[{"value":94,"number":1,"short":"Jan","long":"January"},{"value":94,"number":2,"short":"Feb","long":"February"},{"value":94,"number":3,"short":"Mar","long":"March"},{"value":94,"number":4,"short":"Apr","long":"April"},{"value":94,"number":5,"short":"May","long":"May"},{"value":94,"number":6,"short":"Jun","long":"June"},{"value":94,"number":7,"short":"Jul","long":"July"},{"value":94,"number":8,"short":"Aug","long":"August"},{"value":94,"number":9,"short":"Sep","long":"September"},{"value":94,"number":10,"short":"Oct","long":"October"},{"value":94,"number":11,"short":"Nov","long":"November"},{"value":94,"number":12,"short":"Dec","long":"December"}]},]"meals":55,"zip":null,"county":"","city":"Standard Rate","standardRate":"false"}],"state":"CA","year":2019,"isOconus":"false"}],"version":null}
0
Getting this error when running this script, never worked with PnP before, but this is the error I get at the bottom of the script.  Haven't yielded much searching on this, I have the latest modules installed.

format-default : The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
    + CategoryInfo          : NotSpecified: (:) [format-default], CollectionNotInitializedException
    + FullyQualifiedErrorId : Microsoft.SharePoint.Client.CollectionNotInitializedException,Microsoft.PowerShell.Commands.FormatDefaultCommand

Any suggestions on where I might look what is causing this or what I might be missing is appreciated.  

Full script is located here on GitHub:  https://github.com/SmartterHealth/Virtual-Rounding/blob/master/Scripts/CreateTeamsAndSPO.ps1

<#
DISCLAIMER: 
----------------------------------------------------------------
This sample is provided as is and is not meant for use on a production environment.
It is provided only for illustrative purposes. The end user must test and modify the
sample to suit their target environment. 

Microsoft can make no representation concerning the content of this sample. Microsoft
is providing this information only as a convenience to you. This is to inform you that
Microsoft has not tested the sample and therefore cannot make any representations 
regarding the quality, safety, or suitability of any code or information found 

Open in new window

0
Hi,

I have a date time picker calendar on my site.

what I want is to hide my div when the user select from the date time picker a date
and to show my div when the user does not select from the date time picker date.

this is what I have but it's not working:

<script>
    $(document).ready(function () {

 $('#MigrationDateRequiredDiv').hide();


        $('#MigrationDatePicker').keypress(function(e) {
            e.preventDefault();
        }); 


  $(function () {
            $('#MigrationDatePicker').datetimepicker(
                {
                    format: 'MM/DD/YYYY'
                }
                );
        });




  $("#MigrationDate").on('change', function() {
            if ($("#MigrationDatePicker").val() != '') {
                $('#MigrationDateRequiredDiv').hide();
            }
            else {
                $('#MigrationDateRequiredDiv').show();
            }
        });





    });


</script>



                             <div class='input-group date' id='MigrationDatePicker' style="width:100%;">
                                @Html.TextBoxFor(x => x.MigrationDate, new {@class = "form-control", @style = "width:100%" })
                                <span class="input-group-addon" style="width:0px;">
                                    <span class="glyphicon glyphicon-calendar"></span>
                                </span> 
                            </div>

                            <div id="MigrationDateRequiredDiv"

Open in new window

0
Can someone help me determine why the checkbox on https://www.gtraxc.com/login.asp is disabled?  I can't find the problem.

Thanks!
0
At the times when I almost closed down my programming equipment and take a leave , the code that I created to grab data from a string mixed with Json & Hex failed to pick the data on a laptop , but when returned to the machine where the measurement were done all is fine. Where is the problem in my Ms access VBA 2016?


VBA Code


Dim intFile As Integer
Dim strFile As String
Dim strText As String
Dim strInput As String

intFile = FreeFile()

strFile = "C:\FolderName\FileName.txt"

Dim strFilename As String: strFilename = "C:\Users\chris.hankwembo\Desktop\CPD\test.txt"
Dim strFileContent As String
Dim iFile As Integer: iFile = FreeFile
Open strFilename For Input As #iFile
strFileContent = Input(LOF(iFile), iFile)
strData = strFileContent
Close #iFile
    DoCmd.Save
    Me.ESDTime = Mid(strData, 775, 8) & Mid(strData, 843, 6)
    Me.TerminalID = Mid(strData, 931, 7) & Mid(strData, 998, 5)
    Me.InvoiceCode = Mid(strData, 1086, 7) & Mid(strData, 1153, 5)
    Me.InvoiceNumber = Mid(strData, 1243, 5) & Mid(strData, 1308, 3)
    Me.FiscalCode = Mid(strData, 1393, 10) & Mid(strData, 1463, 10)

Open in new window



The data is attached I cannot believe this?
test.txt
0
I have following JSON file and i need update the displayName to contain either QA or Production :

{
    "analytics": [
      {
        "kind": "Scheduled",
        "displayName": "RO-0024-DEV GPO Scheduled Task",
        "description": "test",
        "severity": "Low",
        "enabled": true,
        "query":"SecurityEvent | where EventID == \"5145\"  | where AccountType == \"User\"",
        "queryFrequency": "5H",
        "queryPeriod": "6H",
        "triggerOperator": "GreaterThan",
        "triggerThreshold": 5,
        "suppressionDuration": "6H",
        "suppressionEnabled": false,
        "tactics": [
          "Persistence",
          "LateralMovement",
          "Collection"
        ],
        "PlayBookName": "Test447"

      }
    ]  
}

Open in new window


i am running a powershell script via Azure Devops build agent and depending on the Tennant, i want to change the DisplayName that contains Dev to QA or Prod.

i have tried the following for testing however it fails:

$rules = Get-Content -Raw -Path .\TestJson.json | ConvertFrom-Json
$rules.analytics.displayname = "test"

Open in new window


i get the following error:

The property 'displayname' cannot be found on this object. Verify that the property exists and can be set.
At line:1 char:1
+ $rules.analytics.displayname = "test"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

Open in new window


Thank you in advance.

Regards,
Kelly
0
Is it possible to Trim the first 4 characters & the second last from the Json string below, the idea here is to remain with pure json, so that if I fail to iterate it , then I can have it printed and posted to the table manually.(Characters not required are  ]    j  and 4c)
Below is the Ms Access VBA code that takes it to text file , but not fully cleaned up.

Text file Export VBA

n = FreeFile()
    Open "C:\Users\chris.hankwembo\Desktop\Leader\test.txt" For Output As #n
    Print #n, strData
    Close #n

Open in new window

Json String

 ]    j{
   "PosVendor": "Nector Prime Accounting Solutions",
   "PosSoftwareVersion": "2.0.0.1",
   "PosModel": "Cap-2017",
   "PosSerialNumber": "100100001829",
   "IssueTime": "20200326115321",
   "TransactionType": 0,
   "PaymentMode": 0,
   "SaleType": 0,
   "LocalPurchaseOrder": "",
   "Cashier": "Admin Manager",
   "BuyerTPIN": "",
   "BuyerName": "",
   "BuyerTaxAccountName": "",
   "BuyerAddress": "",
   "BuyerTel": "",
   "OriginalInvoiceCode": "",
   "OriginalInvoiceNumber": "",
   "Memo": "",
   "Items": [
      {
         "ItemId": 1,
         "Description": "Cleaning Materials",
         "BarCode": 19,
         "Quantity": 1,
         "UnitPrice": 56,
         "Discount": 0,
         "TaxLabels": [
            "A"
         ],
         "TotalAmount": 64.96,
         "IsTaxInclusive": true,
         "RRP": 0
      }
   ]
}4c

Open in new window

0
I am designing an api, which will be called from my front end. say I have a controller method  that calls some other third party api process results and returns json response to the front end ( see sample code below) .

if there is an error in the reques/response and the request is unsucessful to the 3rd party apis, what is best approach. should I return empty json response to the front end , after handling and logging exceptions.

or is it better to send some message so that it can be dealt on the front end. if so can someone share some sample code for this. ?

//get method in some controller
public ActionResult GetData()
{
try
    //call other apis
    //if the response is successful
           return data;
    //if unsucessful
          // ?? what to return to the front end ??
catch
      //log exceptions    
}

front end code ----------------------------------------

$(document).ready(function () {
            $.ajax({
                type: "GET",
                url: "//somecontroller//GetMethod",
                data: param = "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {    
                           //process json data
            }

            function errorFunc() {
                         //do something
            }
       …
0
I am trying to write a small application in PHP do download some content using curl in json format and process it.     Below is the data returned via curl and the error message I get when trying to walk through it.   I am sure it is something small I have done wrong I just cant see it.  

I appreciate any suggestions.  

<?php
$url = "https://website/records";
$apikey = '11111111111111111111111';
$ch = curl_init( $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-KEY: ' .$apikey, 'Content-Type: application/json' , 'Accept: application/json'));
$myout = curl_exec($ch);
curl_close($ch);


//$result = json_decode(json_decode($myout,true));
$result = json_decode($myout);
echo $myout;
$myResult = $result;

foreach($myResult as $value){
       echo $value->name . ",  " , $value->gender . "<br>\n";
}

?>

0
I need help to parse the Json data received from the serial gadget into my Ms Access data base table called ("tblEfdReceiptsPOS") so that, that data can be used for further sales invoices processing that will finally meet tax specification.
At first, I was getting error 1046 from the gadget which I have finally fixed it by editing the highlighted data by the gadget to the correct data.
Now when processing the received data in both the Json & hex format like below I’m not able to put that data into the table mentioned above by using an update query. That is where you help is required.
I have also attached the sample data base so that you can see how the data is being processed and make an informed decision.
Please note the following:
(1)      All double entry systems, financial statements & other essential report have been delinked to avoid confusion.
Example of the correct format for the sent data to the gadget see below, the data received from gadget is in the same format as below:


0000 =  1A 5D 02 00 00 03 5B 7B 0D 0A 20 20 20 22 50 6F | ..]........[{....   "Po
0010 =  73 56 65 6E 64 6F 72 22 3A 20 22 4E 65 63 74 6F | sVendor": "Necto
0020 =  72 20 50 72 69 6D 65 20 41 63 63 6F 75 6E 74 69 | r Prime Accounti
0030 =  6E 67 20 53 6F 6C 75 74 69 6F 6E 73 22 2C 0D 0A | ng Solutions",....
0040 =  20 20 20 22 50 6F 73 53 6F 66 74 56 65 72 73 69 |    "PosSoftVersi
0050 =  6F 6E 22 3A 20 22 32 2E 30 2E 30 2E 31 22 2C 0D | on": "2.0.0.1",..
0060 =  0A 20 20 20 22 50 6F 

Open in new window

0
Here's my attempt to troubleshoot a problem that I have yet to completely track down...

But I'm getting closer!

  if(typeof json !=='undefined') {
				  console.log("you've got some JSON");
				  console.log(json);
				  console.log(json.chartData);
				  if (json.chartData) {
					  buildChart(json.chartData);
				  }    
			  }
			  else {
				  console.log("no json data");
			  }

Open in new window


This is what I get back:

you've got some JSON
null

So, I've got some JSON, but when I try to see it, I get NULL.

I'm thinking I need a better IF statement, but how?

How do I check for both "undefined" and NULL?

I tried this and it didn't work:  if(typeof json !=='undefined' || json !== NULL) {
0
I need help to convert the header 1 , 2 & commandID C++ Code into VBA  so that I can easily code them into a proper VBA serial Packet :
C++ codes
Header1 = The first byte of package header
0x1A

Open in new window

( the C++ code is 0x1A)
Header2 = The second byte of package header
Ox5D 

Open in new window

( the C++ code is Ox5D)
CommandID =
0x 02

Open in new window

as C++ code

Example of the VBA Code for the three above C++ codes

' First two bytes of data packet are always these
   
Const header1 = &H1A
    Const header2 = &H5D
    Const cmdSigning = 2

Open in new window


' Assemble the packet up to final CRC bytes
  dataString = Chr(header1) & Chr(header2) & Chr(cmdSigning) & Dec2Bin(Len(content), 4) & content

Please note the Json Part is 100% correct, its just the first three codes  1A, 5D & 02 are incorrect , that is where help is required here:


Current Dump results:

0000 =  1A 5D 02 00 00 07 75 7B 0D 0A 20 20 20 22 50 6F | ]u{   "Po
0010 =  73 56 65 6E 64 6F 72 22 3A 20 22 4E 65 63 74 6F | sVendor": "Necto
0020 =  72 20 50 72 69 6D 65 20 41 63 63 6F 75 6E 74 69 | r Prime Accounti
0030 =  6E 67 20 53 6F 6C 75 74 69 6F 6E 73 22 2C 0D 0A | ng Solutions",
0040 =  20 20 20 22 50 6F 73 53 6F 66 74 77 61 72 65 56 |    "PosSoftwareV
0050 =  65 72 73 69 6F 6E 22 3A 20 22 32 2E 30 2E 30 2E | ersion": "2.0.0.
0060 =  31 22 2C 0D 0A 20 20 20 22 50 6F 73 4D 6F 64 65 | 1",   "PosMode
0070 =  6C 22 3A 20 22 43 61 70 2D 32 30 31 37 22 2C 0D | l": "Cap-2017",
0080 =  0A 20 20 

Open in new window

0
Why am I getting values Undefined in this page?

http://www.col-b.uk/json/

It is using json_encode.

I am debugging via the console and the array seems fine but individual values are undefined - see screen grab js.jpg.

Here's the code of script.js
$(document).ready(function(){
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(response){
			
            var len = response.length;
				
            for(var i=0; i<3; i++){
                var id = response[i].id;
                var username = response[i].username;
                var name = response[i].name;
                var email = response[i].email;
				
				console.log(response);
				
				console.log(response[i].username);

                var tr_str = "<tr>" +
                    "<td align='center'>" + (i+1) + "</td>" +
                    "<td align='center'>" + username + "</td>" +
                    "<td align='center'>" + name + "</td>" +
                    "<td align='center'>" + email + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

        }
    });
});

[embed=file 1446456]

Open in new window

js.jpg
0
Hello, Experts,

I have a MySQL question. I am a DB admin for all things SQL server and recently started doing full-stack development and using MySQL more.

I have a very basic table that contains three columns (to make the example simple):

------------------------------
| id | ro_number | sales| date |
------------------------------
1 | 2355 | 2000 | 2020-02-15
2 | 2366 | 3500 | 2020-02-16
...

id is int and current PK, set to Not Null, ro_number is also int allow for nulls, sales is dec(13,2).

I am developing a solution that will pull data from an api in a json response, I parse through the data, and prep for loading data in (new records).

What I am after is in the event I need to update historical data, specifically for a date or given dates and I want to update the data if it exists. Should I just do a delete statement for the given date and then pull down the data and insert in again with the new values? or should I do a conditional check?

What say you?

I appreciate your help and excuse my noviceness with all things MySQL.

-Isaiah
0
I would like to output (for curiosity/debugging) the data values in the JSON object returned by Google ReCaptcha v3 verification. The ReCaptcha doc's show the object's format to be:
{
  "success": true|false,      
  "score": number,             
  "action": string,           
  "challenge_ts": timestamp,
  "hostname": string,        
  "error-codes": [...]        
}

Open in new window


Here is code snippet:
<?php
.
.
.
 // post request to verify token with Google reCaptcha server
      //
      $url = "https://www.google.com/recaptcha/api/siteverify";
      $data = array (
        'secret' => $secretKey, 
        'response' => $captcha,
      );
         
      // use key 'http' even if request is to https://...
      //
      $options = array (
        'http' => array (
          'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
          'method'  => 'POST',
          'content' => http_build_query($data)
        )
      );

      $context  = stream_context_create($options);
      $response = file_get_contents($url, false, $context);

      $responseKeys = json_decode($response, true);

     // echo $responseKeys[success];
     // echo $responseKeys[action];
      //echo $responseKeys[score];
 
      if($responseKeys["success"] == true && $responseKeys["action"] == $action && $responseKeys["score"] >= 0.5) {
        echo ("reCaptcha.php thinks you are human");
        header ("location: ./sent-success.htm");
        } else {
          echo ("reCaptcha.php thinks you are a bot");
          header ("location: ./spam-block.htm");
        } 
    ?>

Open in new window


Tried echo $responseKeys[success]; and var_dump($responseKeys. They don't appear to work.
0
Hi,

  We are on Postgres 9.6 version.
I have a table determine_json, that has a column doc_col. Its a Jsonb object and the construct is as below.
 I need to count the number of docId nodes (3 in this example) and display.
Can someone help achieve this?

[
   {
      "docId":"5e319a9146e0fb00c2e1f829",
      "docDesc":"Application Signature Page",
      "docName":"G.Test1.pdf",
      "createdBy":"abc@gmail.com",
      "createdDt":"2020-01-29",
      "updatedBy":"abc@gmail.com",
      "updatedDt":"2020-01-29",
      "memberName":"Mary Ringold",
      "docCategory":"Application",
      "individualId":"915044989",
      "documentTypeCd":"AASP",
      "individualName":"Mary Ringold",
      "docSelectedFlag":null
   },
   {
      "docId":"5e319aa946e0fb00c2253576",
      "docDesc":"Bank Statement",
      "docName":"G.CTest2.pdf",
      "createdBy":"abc@gmail.com",
      "createdDt":"2020-01-29",
      "updatedBy":"abc@gmail.com",
      "updatedDt":"2020-01-29",
      "memberName":"Mary Ringold",
      "docCategory":"Assets",
      "individualId":"915044989",
      "documentTypeCd":"ABS",
      "individualName":"Mary Ringold",
      "docSelectedFlag":null
   },
   {
      "docId":"5e319ab646e0fb00c2e1f82f",
      "docDesc":"Health Insurance Premiums",
      "docName":"G.Test3.pdf",
      "createdBy":"abc@gmail.com",
      "createdDt":"2020-01-29",
      "updatedBy":"abc@gmail.com",
      "updatedDt":"2020-01-29",
      "memberName":"Mary Ringold",
      

Open in new window

0
I am calling a Flask API from React (both running on localhost) and I am running into CORS problems. When the request is made, the browser (Chrome) gives the following error

Access to XMLHttpRequest at 'http://localhost:5000/sas' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

Open in new window


Setup

The Flask setup is the following

from flask_cors import CORS
from flask import Flask, request, Response
from flask_restful import Api, Resource
import json

class SAS(Resource):
    def get(self):
        content = request.json
        js = json.dumps(
            {
                "Response": "Some response"
            }
        )
        resp = Response(js, status=200, mimetype='application/json')
        return resp

app = Flask(__name__)
cors = CORS(app)
api = Api(app)
api.add_resource(SAS, '/sas/')

Open in new window


The call using axios in React is the following

  buttonPressed = async event => {
    event.preventDefault();
    const response = await axios.get(`http://localhost:5000/sas`, {
      data: {
        user: "user",
        file_name: "user",
        directory_name: "user"
      }
    });
  };

Open in new window


NOTE: Running the request from Postman works and shows the header Access-Control-Allow-Origin = *

Any idea on how to solve the problem?

Also, if I was to run the React frontend and API as a dockerized application, I should not see this problem anymore correct?

In this case I would also consider circumnavigating the problem while I am developing
0
I'm  having trouble using the JSON-VBA converter with a key with multiple values.
I have the normal recursion routines written to navigate JSON trees but here's an example of a simple JSON parse which I can't seem to get to work.
See this for the VBA-JSON converter software - which btw is terrific and fast
ools/VBA-JSON]https://github.com/VBA-tools/VBA-JSON

Environment: Win 7 / Access 2016 / Private LAN (no internet)

Here's the code - I've also attached the database itself  -
If anyone can get this working, I would be most appreciative - spending hours on what I'm sure is a trivial solution.

Option Compare Database
Option Explicit

Sub testparse()
Dim js As String, i As Long, jo As Object, item As Variant
Dim keys(), vals()

' fails on this string
js = "{ !Category!: !Famous Pets!," & _
  "!code!: [!a!,!b!,!c!] }"            ' string with multiple values
  
' with the following string, this works
js = "{ !Category!: !Famous Pets!," & _
  "    !code!: !singlecodevalue! }"

js = Replace(js, "!", Chr(34)) ' replace ! with quotes

Debug.Print " js = " & js
Set jo = JsonConverter.ParseJson(js) ' returns object with json elements
i = 0
ReDim keys(1 To jo.Count)
ReDim vals(1 To jo.Count)

Debug.Print " Number keys found at top level " & jo.Count
For Each item In jo
    i = i + 1
    keys(i) = item
    vals(i) = jo(item)
    Next item

For i = 1 To jo.Count
    Debug.Print "key " & keys(i) & " = " & vals(i)
    Next i
    
End Sub

Open in new window

JSON.accdb
0
Hi Experts

Could you point how to obtain the member "valor" and "period_id" from the json above?


{
	"tipoevento_id": 1,
	"user_id": 1,
	"created_at": "2020-03-02 13:08:01",
	"updated_at": "2020-03-02 13:08:01",
	"valor_atual": {
		"id": 1,
		"distribuidor_id": 9,
		"periodo_id": 1,
		"valor": "1000",
		"created_at": "2020-02-20 09:28:47",
		"updated_at": "2020-03-02 13:08:01",
		"mes": 1,
		"ano": 2020
	},
	"valor_anterior": {
		"id": 1,
		"distribuidor_id": 9,
		"periodo_id": 1,
		"valor": "300.0000",
		"created_at": "2020-02-20 09:28:47",
		"updated_at": "2020-02-20 09:28:47",
		"mes": 1,
		"ano": 2020
	},
	"id": 14
}

Open in new window



Thanks in advance!
0
Looking for an example of passing JSON to a server API.  I've had help getting the JSON created from HTML Form Elements, now I need to pass this on to the API.
0
Hi'im getting following Error message most of time.After run the program it's working fine.sometime it's again comming.Any idea much appriciated


Error

WebException: The remote server returned an error: (502) Bad Gateway.
This exception was originally thrown at this call stack:
      System.Net.HttpWebRequest.GetResponse()
    BreezyHRapp_v2.Admin.connectAPI.getAccessToken() in connectAPI.cs
    BreezyHRapp_v2.Candidate.candidateRecords.candidateDetails(string, string) in candidateRecords.cs
      System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
      System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
      System.Runtime.CompilerServices.TaskAwaiter<TResult>.GetResult()
    BreezyHRapp_v2.Candidate.candidateClient.candidateDetails(string[]) in candidateClient.cs



string url = "/company/"+ companyID +"/position/"+ positionID + "/candidates";
            var request = new RestRequest(url, Method.GET);


            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("authorization", connectAPI.getAccessToken());



public static string getAccessToken()
        {
            _restClient = new restClient();
            string path = _restClient.SigninUrl;
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(path);
            httpWebRequest.ContentType = 

Open in new window

0
Hi,

I need your help please.

I'm trying to validate an email address

function ValidateData() {
        //debugger;
        var StartCreateDate = $('#FromCreatedDate').val();
        var EndCreateDate = $('#ToCreatedDate').val();
        var StartMigrationDate = $('#FromMigrationDate').val();
        var EndMigrationDate = $('#ToMigrationDate').val();
        var SendToEmail = $('#SendEmailTo').val();
       
        if ((StartCreateDate != null && EndCreateDate != null) && (StartCreateDate > EndCreateDate)) {
            alert("From create date must be greater than to create date")
            return false;
        }
        if ((StartMigrationDate != null && EndMigrationDate != null) && (StartMigrationDate > EndMigrationDate)) {
            alert("From migration date must be greater than to migration date")
            return false;
        }
        if (SendToEmail "doesn't have the correct format")  //Here I want to validate my email address $('#SendEmailTo').val();
        {
            alert("Email format is incorrect")
            return false;
        }

        return true;
    }

Open in new window



Thank you,
0
I need to build an html form that collects data entered from the user and then creates json to be used for an API call.  The format that the JSON needs to placed in is hierarchical and I'm not sure how to do that.

This is what the JSON should look like and each value should be coming in from the html form.  

{
"request": {
        "subject": "Unable to fetch mails",
        "description": "I am unable to fetch mails from the mail server",
        "requester": {
            "id": "4",
            "name": "administrator"
        },
        "impact_details": "Routine tasks are pending due to mail server problem",
        "resolution": {
            "content": "Mail Fetching Server problem has been fixed"
        },
        "status": {
            "name": "Open"
        }
    }
}'

Open in new window

0
Hi

I am working on an application to access data via API using VB.NET.

I have so far managed to request for and retrieve a security token in the format as shown below:

{"success":true,"token":"eyJhbGciOiJIUzI1NiIsImNhbGciOiJERUYifQ.eNqqVkpOyc9NzMxTslLKTcxJrCzOTDRU0lFKrShQsjI0tTACYjNT01oAAAAA__8.ElaYAGRsAV43lh2OyQ4eR1wF4UIKl7tpHS7YFamVGD8"}

I need to retrieve the "token" value and use that to access the server and request specific information.

I have created a class


Public Class SecurityToken

    <JsonProperty("success")>
    Public Property Success As String

    <JsonProperty("token")>
    Public Property Token As String()

End Class

And in my code, I successfully get to this point where I get the result as shown above


Dim dataStream As Stream = response.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()

I am stuck at this point in trying to split the result and retrieve just the token to use in further processing.

Any help would be appreciate.

Thank you.
0

JSON

1K

Solutions

953

Contributors

JavaScript Object Notation, or JSON, is human-readable text used when transmitting data objects consisting of attribute:value pairs between a server and a web application as an alternative to XML. JSON, while it is originally derived from JavaScript, is a language-independent data format. Code for parsing and generating JSON data is available in many programming languages.

Related Topics