JSON

857

Solutions

842

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.

Share tech news, updates, or what's on your mind.

Sign up to Post

Here's my code:

const fs = require("fs");
const path = require("path");

module.exports = class Product {
  constructor(t) {
    this.title = t;
  }

  save() {
    const p = path.join(
      path.dirname(process.mainModule.filename),
      "data",
      "products.json"
    );
    fs.readFile(p, (err, fileContent) => {
      let products = [];
      if (!err) {
        products = JSON.parse(fileContent);
      }
      products.push(this);
      fs.writeFile(p, JSON.stringify(products), err => {
        console.log(err);
      });
    });
  }

  static fetchAll() {
    return products;
  }
};

Open in new window


The error that I'm getting is:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at fs.readFile (C:\wamp\www\adm\node\express_tutorial\models\product.js:18:25)
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
[nodemon] app crashed - waiting for file changes before starting...

This is line #18: products = JSON.parse(fileContent);

Two questions: First of all, what am I missing that would result in the error that I'm getting?

Secondly, what is "18:25?" I'm referring to the actual error message. "18," I'm assuming, is line #18, but what is "25?"

Thanks!
0
JavaScript Best Practices
LVL 13
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

I am pulling data from an API and I believe it is returned as a JSON string, how can I read certain data from the string ?  There are rows of data I want to loop through and put in a datatable, but can not figure out how to extract the data.

I have attached 3 files - the first 2 is the data I want to access, the third is the name of the columns.

Path to Column NamesWhere the data is - Label and Value are two fields inside I want to access.Path To Data
0
Hello everyone,
I am faced with a small problem and ask for your help.
In order to estimate the amount of a transport according to the weight of a package, I set up a fee schedule that takes into account the total amount per zone as a result:

Poids_min	Poids_max	ZoneA	ZoneB	Zone1	Zone2	Zone3	Zone4	Zone5	Zone6	Zone7	Zone8
0		0.5		0	0	11399	11564	11895	13712	14703	15034	15694	17016
0.501	1		0	0	11399	11564	11895	13712	14703	15034	15694	17016
1.001	1.5		0	0	11399	11564	11895	13712	14703	15034	15694	17016
1.501	2		0	0	11399	11564	11895	13712	14703	15034	15694	17016
2.001	2.5		0	0	18503	18998	20981	22963	25111	26432	27424	29076
2.501	3		0	0	22302	22963	25276	27589	30067	31719	33040	35023
3.001	3.5		0	0	26102	26928	29571	32214	35023	37005	38657	40970
3.501	4		0	0	29902	30893	33866	36840	39979	42292	44274	46917
4.001	4.5		0	0	33701	34858	38162	41466	44935	47578	49891	52864
4.501	5		0	0	37501	38822	42457	46091	49891	52864	55508	58812
5.001	5.5		0	0	39483	40970	45100	49065	53195	56499	60133	63602
5.501	6		0	0	41466	43118	47743	52038	56499	60133	64759	68393
6.001	6.5		0	0	43448	45265	50386	55012	59803	63768	69384	73184
6.501	7		0	0	45430	47413	53030	57986	63107	67402	74010	77975

Open in new window


Here is what corresponds to my PHP code that returns a json result:
<?php
$c_Table = !empty($_POST['c_Table']) ? $_POST['c_Table']: NULL;
$c_Weig = !empty($_POST['c_Weig']) ? $_POST['c_Weig']: NULL;
$c_Deli = !empty($_POST['c_Deli']) ? $_POST['c_Deli']: NULL;
$c_Zone = !empty($_POST['c_Zone']) ? $_POST['c_Zone']: NULL;

$result = array();

if($c_Table){

  $sql = "SELECT `".$c_Zone."` FROM `".$c_Table."` WHERE $c_Weig BETWEEN Poids_min AND Poids_max "; 

try{
    $Stat = $pdo->prepare($sql);
    $Stat->execute();
    $result['success'] = $Stat->fetchAll(PDO::FETCH_ASSOC);
  }
	catch(PDOException $e)
	{$result['Error'] = "<div class='alert alert-danger'>".$e->getMessage()."</div>";}
}

echo json_encode($result);
exit();
?>

Open in new window


Until then everything works great except that I would like to add something else and that's why I'm here.
DHL offered me a price reduction in case the orders are >= 50Kg.
DHL proposes to give me the Kilo at 9300 for the Zone8, 9200 for the Zone7, 9100 for the Zone6... and so on until the zone1.

ZoneA and ZoneB remain 0.

That's a bit of what I'm facing.
Thank you for your help.
Regards,
Jaber
0
I have the following codes on mvc code behind, and have I have two questions.

1. string returnStrInHTML = sa.AgingInDetailsInHTML(agingInDetail) is return string in <html> codes.
how can I return as Json or xml format?

2. With current codes, I also have exceeding max size as well. I think it is because the HTML codes is too big.
I did make the changes on web config but still not working. How to fix it?

	[HttpPost]
        public JsonResult GetAgingReport(string invoicestartandenddate, string receiptstartandenddate, string assoication, string chargecode)
        {
            string[] invoiceStartEndDateList = invoicestartandenddate.Split('-');
            Int64 invoicestartdate =MasterHelper.Generic.CustomDateFormat(invoiceStartEndDateList[0]);
            Int64 invoiceenddate = MasterHelper.Generic.CustomDateFormat(invoiceStartEndDateList[1]);

            string[] receiptStartEndDateList = receiptstartandenddate.Split('-');
            Int64 receiptstartdate = MasterHelper.Generic.CustomDateFormat(receiptStartEndDateList[0]);
            Int64 receiptenddate = MasterHelper.Generic.CustomDateFormat(receiptStartEndDateList[1]);

            Domain.Accounting.Report r = new Domain.Accounting.Report();             
            r.invoicestartdate = invoicestartdate;
            r.invoiceendate = invoiceenddate;
            r.receiptstartdate = receiptstartdate;
            r.receiptenddate = receiptenddate;
            r.chargecode = chargecode;
            

Open in new window

0
I need to be able to run the following in visual studio using vb.net. :

# Use the command below to dump the JSON data for your orders. Replace the `2c493d74` with your own API key (which will be much longer)
curl -u 2c493d74:X "https://app.handshake.com/api/latest/orders"

Make sure to replace the 2c493d74 with your own API key.
I downloaded https://curl.haxx.se/download.html and it does run

I have been playing about with code like the following as well.

   Dim credstring As String = "apikey:X"
            Dim authstring As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(credstring))

            Dim webrequest As WebRequest = webrequest.Create("https://app.handshake.com/api/latest/orders")

            With webrequest
                .Headers.Add("Authorization", "BASIC " & authstring)

                Dim webresponse As HttpWebResponse = .GetResponse() '

                Dim stream As System.IO.Stream = webresponse.GetResponseStream()
                Dim reader As New StreamReader(stream, Encoding.UTF8)
                Dim contents As String = reader.ReadToEnd()
                Debug.Print(contents)
            End With

Just looking for the easiest solution. Been searching for CLIB integrations into vb.net.

Best Regards,

Ross
0
Looking at integrating a vb.net application to pull orders from a web API. In the past I have added a reference and used the WSDL. The software I am trying to integrate is:

http://docs.handshake.com/?json-doc#quickstart

It would be better if I could use a WSDL type integration but from the documentation it looks like you have to do a HTTP request.

Really looking for the best way to move this forward. don't know if I should use the HttpWebRequest.

The documentation says :
# Use the command below to dump the JSON data for your orders. Replace the `2c493d74` with your own API key (which will be much longer)
curl -u 2c493d74:X "https://app.handshake.com/api/latest/orders"


I am a bit unsure if I keep my httpwebrequest as:        
Dim myRequest As HttpWebRequest = CType(WebRequest.Create("https://app.handshake.com/api/latest/orders"), HttpWebRequest)

If I try and anything else it fails. I can call myRequest.Credentials but is this what I should be trying to do?


Best Regarsd,

Ross
Example.JPG
0
I'm looking for some good learning resources for Json and Java to shorten some tasks.  Also looking for something on Node and Java.  Any suggested books or websites to learn this stuff?  By the way what application does Json and Node have?


Thanks!
0
I have JSON type data stored in a column in a SQL Table (Microsoft SQL).  I would like to be able to extract each element.
DATA:
{"amount":"0.52","invoiceNumber":"212265","result":"APPROVAL","txnId":"160119E3C-39EC4068-0571-41CC-9146-4FFCE637C30B","approvalCode":"060507","txnTime":"01/16/2019 01:14:00 PM"}

Is there a way to write a query that would extract the invoiceNumber, amount, and approvalCode Values easily?

Thanks
0
{
 "id": "169535ddb258a889",
 "threadId": "1695350fe63f9f3a",
 "labelIds": [
  "IMPORTANT",
  "CATEGORY_PERSONAL",
  "INBOX"
 ],
 "snippet": "this is a test On Wed, 6 Mar 2019 at 14:03, &lt;alextestemail21@gmail.com&gt; wrote: Hello ( user ) Thank you for filling in our form, if you have any questions please feel free to contact me on this",
 "historyId": "20762",
 "internalDate": "1551881841000",
 "payload": {
  "partId": "",
  "mimeType": "multipart/related",
  "filename": "",
  "headers": [
   {
    "name": "Delivered-To",
    "value": "alextestemail21@gmail.com"
   },
   {
    "name": "Received",
    "value": "by 2002:ab0:7509:0:0:0:0:0 with SMTP id m9csp5885537uap;        Wed, 6 Mar 2019 06:17:34 -0800 (PST)"
   },
   {
    "name": "X-Received",
    "value": "by 2002:a2e:12da:: with SMTP id 87mr2575789ljs.181.1551881853887;        Wed, 06 Mar 2019 06:17:33 -0800 (PST)"
   },
   {
    "name": "ARC-Seal",
    "value": "i=1; a=rsa-sha256; t=1551881853; cv=none;        d=google.com; s=arc-20160816;        b=q7Ps0TS3Z/E88kwwhmJyMzyi6CXgW8iAgOFF68UPoBHDBW13fcl4G83CvLXyxteSG3         k4Js2xpLxF5tw4XIZQIODYNfvzx1wjs3vk8J9XYE58jzjujQRiM9rOZGSGB9Cn3n8ifP         CfLRPwHsv6KjReJ6b6bCABD14DkbX8VzQ7MZ9YWjj0x1YtLW2iAjCxfcBSwR8CHeJ3V7         VUfF8dPsMBGG5Wrwbp3lyDak6zZS7JbysKtmSIhgBoVbUvSU6UFlB3bo/Rfffex+zQFQ         HkGjnp0OxBsEKRb4MGlTYI2QIrS/BFbpMsHLyBizAz4Sgt4ZW88MTlc57st8WBcjmvPF         avsg=="
   },
   {
    "name": "ARC-Message-Signature",
    "value": "i=1; 

Open in new window

0
We currently use Terraform and wanted to find out if there is a command within Azure Arm Templates in which you could use the Terraform Plan equivalent command in the ARM JSON world. So basically a test is required to check what the code is actually going to do the live environment before it is executed, basically like Terraform Plan.
0
OWASP: Avoiding Hacker Tricks
LVL 13
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Having trouble parsing JSON data in Azure Stream analytics for PowerBI, My device message data is passed to my IOT hub through an MQTT server in JSON format, the message data gets sent in with the following format.
{
  "body": {
    "timestamp": 1551731885318,
    "values": [
      {
        "id": "Channel2.Device1.Rtag1",
        "v": 26738,
        "q": true,
        "t": 1551731884050
      }
    ]
  },
  "applicationProperties": {
    "topic": ""
  }
}

Open in new window


My Azure Stream Analytics query currently just uses a wildcard to scan this message, and routes each message directly to powerBI unchanged.

[{"body":{"timestamp":1551726708054,"values":[{"id":"Channel2.Device1.Rtag1","v":25520,"q":1,"t":1551726704055}]},"applicationProperties":{"topic":""}}]

Current Query
The problem, is when this gets passed to PowerBI, if I chart Timestamp/Value, then each timestamped datapoint on the chart will be valueless, as the corresponding value is "array".

I need to edit my query to pass the "v":25520, along to power BI rather than the entire array.

I understand the JSON hierarchy, but am new to SQL and am not sure how to pass the different values within my device message as separate properties that can be selected in PowerBI
0
Hi Experts,

I need to help on writing the C# code develop a following solution.

Basically my requirement is to export the files to another application through restful web-service call (POST).

They provided following  :
URL ( Insert document service )
its restful web service call  - POST

They are expecting the request  multipart/Mixed  with json structure.

Please let me know if any questions.

Regards,
Kumar
1
Hi Experts,

I need help on restful web service testing in the soap UI.

Request type : POST

How to add the json structure in the multipart/mixed request to test in the soup UI.
in the soup UI - we have the media type - any one we can choose from the drop down.. but is there any way that we can pass json structure in the multipart/mixed request .

Let me know if you have any questions.

Regards,
Kumar
0
I have a service which has a REST endpoint which returns a simple LIST containing Events and the event descriptions. I have been asked to return the output in standard JSON format. Is this just a matter of adding , RequestFormat = WebMessageFormat.Json &    ResponseFormat = WebMessageFormat.Json to the operation contract or is there more to it than this ?
0
I have a code in java and need to write it in C # please help me. Thank you

import org.junit.Assert;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class BrowserProfile {
    public static void main(String[] args) throws Exception {
        BrowserProfile bp = new BrowserProfile();
        //TODO replace with existing profile ID. Define the ID of the browser profile, where the code will be executed.
        String profileId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

        //Define DesiredCapabilities
        DesiredCapabilities dc = new DesiredCapabilities();

        //Instantiate the Remote Web Driver to connect to the browser profile launched by startProfile method
        RemoteWebDriver driver = new RemoteWebDriver(new URL(bp.startProfile(profileId)), dc);

        //Perform automation
        driver.get("https://multilogin.com/");
        Assert.assertEquals("Multilogin - Replace Multiple Computers With Virtual Browser Profiles - Multilogin",driver.getTitle());
        driver.quit();
    }

    private String startProfile(String profileId) throws Exception {
        /*Send GET request to start the browser profile by profileId. Returns response in the following format:
        '{"status":"OK","value":"http://127.0.0.1:XXXXX"}', where XXXXX is the 

Open in new window

0
Having trouble deploying an SPFx custom application extension.  After I build and add it to my CDN,  I add it to my app catalog and all seems okay.  I then go to a site collection and attempt to add the app.  When I select it to add I get this error on the tile:

"SPFX application extension Sorry, something went wrong with adding the app"

No idea why or what to do.  I have gone over the code and various JSON files several times and don't see the cause.
0
I'm trying to pass props from Parent ("Section") element to all Children elements while trying to make sure that only "Block" elements can be used as children. It works fine when I use React.cloneElement the following way:
const Blocks = React.Children.map(children, child => {
      return React.cloneElement(child, {
        type: this.props.type,
      });
    });

Open in new window


But when add the validation the following way:

const Blocks = React.Children.map(children, child => {
      if (child instanceof Block) {
        return React.cloneElement(child, {
          ...this.props,
        });
      } else {
        console.log('not a block');
        console.log(child);
      }
    });

Open in new window


No content shows up at all. But when I use the validation code the following way:

const Blocks = React.Children.map(children, child => {
      if (child instanceof Block) {
        return React.cloneElement(child, {
          ...this.props,
        });
      } else {
        console.log('not a block');
        console.log(child);
      }
    });

Open in new window


But when I do it the following way, all elements show up double/twice:

const Blocks = React.Children.map(children, child => {
  if (child.type === Block) {
    return React.cloneElement(child, {
      ...this.props,
    });
  } else {
    console.log('not a block');
    console.log(child);
  }
});

Open in new window


As this output image:

double-trouble-cloneElements.JPG
I'm pretty new to this. Not sure what I'm doing wrong here. Any help on this will be appreciated. Thanx.
0
I am trying to think of a way to save a JSON object onto the a web page without displaying it to the end user.  The purpose would be to save the object until another function calls it like a button.  This would be used to push the value to a POST action.  Would it be better to save the entire JSON object or a string id value?
0
I am receiving the following XML as a result of the HTTP GET function from the B2B supplier.
I need to process this file in the Azure LogicApp and get the invoice IDs, so I can use them to download each invoice using another LogicApp and another URL with GET method.

<Invoices xmlns="http://gateway.com/schemas/Invoices" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://gateway..com/schemas/Invoices Invoices.xsd">
   <DocumentInfo>
      <DocType>INVOICES</DocType>
      <DocVersion>2.0</DocVersion>
   </DocumentInfo>
   <Header>
      <StartDate>2018-12-01T00:00:00+01:00</StartDate>
      <EndDate>2019-01-03T00:00:00+01:00</EndDate>
   </Header>
   <Documents>
      <Invoice InvoiceId="RP82807" InvoiceDate="2019-01-02T00:00:00+01:00" DocumentType="IN" RefDocId="FT34532" RefDocType="ORDER" SystemId="10" HasPDFImage="0" />
      <Invoice InvoiceId="T609881" InvoiceDate="2018-12-31T00:00:00+01:00" DocumentType="IN" RefDocId="FT39339" RefDocType="ORDER" SystemId="0" HasPDFImage="0" />
   </Documents>
</Invoices>

Open in new window


Based on this article I've created the liquid map file to get the list of invoice IDs:
{
"Invoice": "{{content.Documents.Invoice}}"
}

Open in new window


When using it in the LogicApp in the XML->Json converter, got the following result:
{
    "Invoice": ""
}

Open in new window


I have also tried this as a liquid file:
{
"Invoice": "{{content.Invoices.Documents}}"
} 

Open in new window


and this:
{
"Invoice": "{{content.Invoices.Documents.Invoice}}"
}

Open in new window


with the same result.
I have also tried the XSLT file which I found here.
As a result, I got this error:

Open in new window

0
OWASP: Forgery and Phishing
LVL 13
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Using VBA - I need to write a REST/POST command with JSON parameters.  However, I can't seem to find a simple example that I can follow.  Does anyone have anything?
0
Experts,
 We have requirement to formatting sharepoint 2013 list view header and footer with client side code. We would like to have change OOB paging. Ca you please help with me with some code to change formatting with client side rendering.

After.PNG
Thank You
0
I'm using mobx-state-tree
What I want to know is  what the difference is 'getSnapshot' and 'toJSON'.
I think both of them are doing same role that returns json format data.
ex)
between
var jsonData = getSnapshot(chatsStore.userInfo)
  and
var jsonData = chatsStore.userInfo.toJSON();
       
What's difference??
0
upload.html
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Import CSV File into Jquery Datatables using PHP Ajax</title>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
    </head>
    <body>
      <div class="container">
   <br />
   <h3 align="center">Mark distribution Sheet</h3>
   <h3 align="center">Cisco Discovery 1</h3>
   <br />
<form action="import.php" method="post" enctype="multipart/form-data">
<div class="col-md-3">
     <br />
     <label>Add More Data</label>
    </div>
      <div class="col-md-4">  
            <input type="file" name="csv_file">
                  </div>  
      <div class="col-md-5">
            <input type="submit" value="Upload">
                  </div>  
        </form>
      <br />
   <br />
   <div …
0
I would like to update fields in an existing group the custom fields in WordPress more quickly  in a "BATCH form" did anyone here mange to do it without messing up.
for example I want to start with adding extra text fields to an existing group,
Maybe MYSQL request ?
Maybe JSON request.
has anyone done this ?
0
Is this code convertible to print it's results to a txt file, instead of to a JSON ?curl object? We are trying to debug a specific sku and we want to see the output of the long query which precedes this snippet:

         foreach($group_sets AS $group_set) {
            $bulk_json .= '{ "index" : { "_id" : "'.$group_set['our_sku'].'" } }'.PHP_EOL;
            $bulk_json .= json_encode($group_set).PHP_EOL;   
         }	
         foreach($remove_skus AS $sku) {
            $bulk_json .= '{ "delete" : { "_id" : "'.$sku.'" } }'.PHP_EOL;     	     
         }
         print "processing batch, batch count: ".$batch_cnt.PHP_EOL;
         send_to_elastic($bulk_json);
         $bulk_json = ""; 
         $batch_cnt = 0;
         $batch_sku_list = array();
      }
   }
   if(!empty($bulk_json)) {
      send_to_elastic($bulk_json);
      $bulk_json = ""; 
   }

   print PHP_EOL.PHP_EOL."DONE".PHP_EOL.PHP_EOL;
      
   function send_to_elastic($bulk_json) {
         $url = "https://ada64ff1913a4b.us-east-1.aws.found.io:9243/us/product/_bulk";


         $curl = curl_init($url);
         curl_setopt($curl, CURLOPT_HEADER, false);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($curl, CURLOPT_USERPWD, "MyName:MyPassword");
         curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
         curl_setopt($curl, CURLOPT_POST, true);
         curl_setopt($curl, CURLOPT_POSTFIELDS, $bulk_json);

         echo "uploading 

Open in new window

0

JSON

857

Solutions

842

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.