JSON

960

Solutions

900

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

Hi Experts,
I would like to extract the pay_interval field value from the JSON array into MYSQL syntax :
[
  {
    "111_id": 238777,
    "222_no": "I-86605",
    "333_item": [
      {
        "444": "Contract Rate",
        "555": "Hours",
        "666": "210.00",
        "777": "12.00",
        "888": "17.50",
        "999": "42.00",
        "2222": "252.00",
        "3456": "1234invoice_no": "INV-1",
        "54345": "90"
      }
    ],
    "pay_interval": 1,
    "888": "Unpaid",
    "t999": 210,
    "000_id": 29669,
    "234_id": 4393
  }
]

Open in new window

Any help would be appreciated
Thanks
0
Introduction to R
LVL 13
Introduction to R

R is considered the predominant language for data scientist and statisticians. Learn how to use R for your own data science projects.

Dear All;

Sorry I thought putting header was just simple in json converted data , but has proved to destroy all my effort so far . I'm now required to rearrange the Json data from screen shoot below to have the following:

(1) The customer name & address MUST only appear on top of the receipt NOT on every item.
(2) List of products must have category called ITEMS


Example

{
"Customer": "J j Zingalume ",
"Address": "Lusaka West",
"Items:[
{
  "Item":"1"
 "Description": "Rice"
"Quantity":"10"
"UnitPrice":"51"
"Total":"510"
}
]
}

Open in new window

Kindly note that Im using the Json converter in  Ms Access, that is why I have these challenges.


DataArrangements.png
0
I have the following json string. how  to read it in c# FOR  LOOP?

{Employee:[{"principalfirstname":"xxx","principallastname":"xxx","principalmiddlename":"xxx","principalnameonbond":"xxx","principaldba":"xxx","principalentity":"USA","principalyearinbusiness":"xxx","principaltaxid":"","principaladdress":"xx","principalcity":"xxx","principalstate":"TN","principalzip":"111","principalcounty":"","principalphoneno":"xxx","principalemail":"","principalfaxno":"","vin":"","licenseplatenumber":"","driverlicensenumber":"","door":"","bondstate":"","bondamount":"","premium":"","bondterm":"","creditcardfullname":"","creditcardnumber":"55555555533331111","creditcardchargeamount":"","creditcardexpdatemm":"","creditcardexpdateyyyy":"","creditcardcvc":"","creditcardaddress":"","creditcardcity":"","creditcardstate":"","creditcardzip":""}]}

Open in new window

0
I have this string in json {"columnC":"1","columnA":"2","columnB":"2"}
How can I use for loop to generate  like

ColumnC: 1
ColumnA: 2
ColumnB: 2

Thanks
0
I have Json & MVC / c# question below:

the var json = JSON.stringify(data); return json format
like {"column":"1","columnA":"2"}

My question is inside of the C# mvc ReceiveJson: How to extract the value like

column = 1
columnA = 2

and i want to be like insert table column, columnA values (1,2)

And {"column":"1","columnA":"2"} is it a json format?

*** formdiv *** inside of it, it just a combination of some <input id='column'> or <select id='columnA'>
function Submit(domain) {
    var x = $('#formdiv *').serializeArray();
    var data = {};
    $.each(x, function (i, field) {
        data[field.name] = field.value;
    });
    var json = JSON.stringify(data);
    alert(json);
    $.ajax({
        url: domain + "/Api/ReceiveJson",
        type: "POST",
        data: {
            'message': json
        },
        dataType: 'json',
        success: function (data) {
            alert(data.BondCode);
        },
        error: function (msg) { alert(msg); }
    });
    return false;
}

[HttpPost]
        public JsonResult ReceiveJson(List<string> message)
        {             
            var jsonResult = Json(message);
            domainCompanyBondType.BondCode = "1";
            return Json(domainCompanyBondType, JsonRequestBehavior.AllowGet);
        }

Open in new window

0
I have the following ajax codes, and want to send Json data to MVC Controller.
Can you show me how to do that  on MVC Controller?
Thanks

function Submit(domain) {
    //alert("Thank You");
    var x = $('#formdiv *').serializeArray();      
    var data = {};
   $.each(x, function (i, field) {
        data[field.name] = field.value;
   });
    var json = JSON.stringify(data);   
    alert(json);
    $(document).ready(function () {
        $.ajax({
            url: domain + "/Api/ReceiveJson",
            type: "POST",
            data: {json},
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (data) {alert('Success');},
            error: function (msg) { alert(msg); }
        });
    });
    return false;
}

Open in new window

0
I have a thirdparty rest api and angular js frontend project that I inherited.

data is in json, and the code iterates over the collection and displays it.
as I don't have control over the api and what it returns , I want to hide certain items in the collections.

what are my options in angularjs?
0
Dear Experts

Kindly see how you can help again in my final part of this Ms Access /Json project, now I want the data in the query below to be posted to the site as per link in the VBA. The problem I have right now is how to format the data in a query into Json so that it can be posted successfully
Qry1
SELECT tblInvoice.Customer, tblCustomers.TaxID, tblCustomers.Address, tblInvoice.INV, tblInvoice.InvoiceDate, tblInvoicedetails.Product, tblInvoicedetails.Qty, tblInvoicedetails.Price, tblInvoicedetails.VAT, (([Qty]*[Price])*(1+[VAT])) AS TotalPrice
FROM tblProducts INNER JOIN ((tblCustomers INNER JOIN tblInvoice ON tblCustomers.ID = tblInvoice.Customer) INNER JOIN tblInvoicedetails ON tblInvoice.INV = tblInvoicedetails.INV) ON tblProducts.PDID = tblInvoicedetails.Product
WHERE (((tblInvoice.INV)=[Forms]![frmInvoice]![INV]));

Open in new window


Below is the VBA that I have prepared requiring completing the Json data formatting:

Private Sub CmdSales_Click()
Dim http As Object
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Dim JSON As Object
Dim i As Integer
Dim item As Object
Set rs = db.OpenRecordset("SELECT * FROM Qry1 Where Qry1.ID = " & Me.INV, dbOpenDynaset, dbSeeChanges)
http.Open "POST", "http://jsonplaceholder.typicode.com/users/?id=" & Me.INV, False
http.send
Set JSON = ParseJson(http.responseText)
i = 2
End Sub

Open in new window

Kindly see how this can be done!
0
I'm trying to figure out how to serialize an array of java objects and post as json with jax-rs ClientBuilder using jersey and/or jackson.

I'm using the ClientBuilder to do a post. If for example you have an Arraylist of Car objects

List<Car> cars = new ArrayList<>();

Open in new window

And I want to do something like:

Response response = ClientBuilder
.newClient.target(url)
.request()
.accept(MediaType.APPLICATION_JSON)
.post(Entity.json(cars));

Open in new window

and post exactly this as the payload

[{"brand": "toyota"}]

Open in new window

How would I need to implement the Car object? And how would I need to setup my ClientBuilder chain properly?
0
I'm building an OpenAPI spec and it's really very basic. All I'm having to do is document the fact that I've got an JWT embedded within the header of an incoming request. I'm going to process it and respond with either a 200 or an error.

I'm using APICurio to put it all together and the screenshot below demonstrates my troubles.

screenshot of OpenAPI
The fact that there's "The Authorization" head parameter will be ignored" warnings tell me I'm doing something wrong.

I've googled for examples but I can't find anything.

Can anyone point me in the direction of how to document an Open API that shows a basic authorization process where a JWT within the header is being retrieved and evaluated?

Thanks!
0
Fundamentals of JavaScript
LVL 13
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Team,

Need your urgent help on this.

I am testing this below PS script to populate desired value infront of Office location  in SPO user profile.

Under this URL to update the SPO user profile properties.

https://github.com/SharePoint/PnP/blob/master/Samples/UserProfile.BatchUpdate.API/CreateImportJob.ps1

I have mentioned

$propertyMap.Add("Property1", "sps-location")

in json file:
{
    "value": [
        {
            "IdName": "user1@domain.com",
			"Property1": "VTM",
        },
        {
            "IdName": "user2@domain.com",
			"Property1": "VTM",
        },
		{
            "IdName": "user3@domain.com",
			"Property1": "VTM",
        },
        {
            "IdName": "user4@domain.com",
			"Property1": "VTM",
        }
    ]
}

Open in new window




But I am getting an error as:

Exception calling "ExecuteQuery" with "0" argument(s): "File Not Found."
At line:43 char:1
+ $context.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ServerException




Any help would be greatly appreciated.

Thanks in advance
0
Need to change a value in a Package.json file that looks like this
package.json  
{
  "name": "Test",
  "version": "0.1.0",
  "repository": {
    "type": "git",
    "url": "git@github.com/test.git
  },
  "license": "UNLICENSED",
  "private": true,
  "devDependencies": {
    "chromedriver: "75"
}


Below code gives me chrome driver version 75
CHROME_VERSION=$(cat package.json \
  | grep chromedriver \
  | head -1 \
  | awk -F: '{ print $2 }' \
  | sed 's/[",]//g')

echo $CHROME_VERSION


Using a bash script - can anyone help me with how to update the value from 75 to 76?

I need to update the chrome driver version from 75 to 76. (Update the chrome driver version from 75 to 76)
0
Hi;

I am trying to get value of loglevel and logType from below json logs of ElasticSearch by using Nest Code. LogLevel should be "ERROR" LogType should be "Response". How can I write this Nest query. I think that Nest is Really difficult.


            var settings = new connectionsettings(new uri("http://localhost:9200")).defaultındex("mylog-2019-07-29");

            var client = new elasticclient(settings);

            var searchresponse = client.search<rootobject>(s => s
                                            .allındices()
                                            .from(0)
                                            .size(10)
                                            .query(q => q
                                                 .match(m => m
                                                    .field(f => f.logLevel)
                                                    .query("Error")
                                                 )
                                            ));

            var r3 = client.search<rootobject>(search => search.matchall().ındex("mylog-2019-07-29")).documents;

			// OR 
            var result = client.search<rootobject>(q => q.allındices());
            var result2 = result.hits;

            using (httpclient client = new httpclient())
            {
                var result = await client.getasync("http://localhost:9200");

                var data = 

Open in new window

0
Hi, I have json string and I want to parse in vb.Net so I can select individual values, What will be simplest way to do that, I am attaching my code
Dim serviceUrl As String = "http://localhost:61210/Webservice/PService.svc"
        Dim input As Object = New With { _
                        .UserId = "14"
        }
        Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input)

        Dim httpRequest As HttpWebRequest = DirectCast(WebRequest.Create(New Uri(serviceUrl & "/InsertLogInLog")), HttpWebRequest)
        httpRequest.Accept = "application/json"
        httpRequest.ContentType = "application/json"
        httpRequest.Method = "POST"

        Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson)

        Using stream As IO.Stream = httpRequest.GetRequestStream()
            stream.Write(bytes, 0, bytes.Length)
            stream.Close()
        End Using
        Dim strText As String

        Using httpResponse As HttpWebResponse = DirectCast(httpRequest.GetResponse(), HttpWebResponse)
            Using stream As IO.Stream = httpResponse.GetResponseStream()
                strText = (New StreamReader(stream)).ReadToEnd()
            End Using
        End Using

Open in new window

0
I am using ASP.NET 4.7 (not ASP.NET Core) to design a web page, which receive Webhook request from Dialogflow. I use following code to extract the JSON data from request.

using (var reader = new StreamReader(Request.InputStream))
{
    string reqString = reader.ReadToEnd();
}

Open in new window


However, I found the double quotes in the original request are missing in the content. Original message is

{"responseId":"0b0b6903-60be-4fdf-919b-f20103bfd1ec-21947381","queryResult":{"queryText":"I need to book a hotel room with queen size bed.","parameters":{"size":"queen"},"allRequiredParamsPresent":true,"fulfillmentMessages":[{"text":{"text":[""]}}],"intent":{"name":"projects/aets-mknkjs/agent/intents/1727505d-2499-42c4-95ec-7385b5da17a3","displayName":"hotelbooking"},"intentDetectionConfidence":0.7410408,"languageCode":"en"},"originalDetectIntentRequest":{"payload":{}},"session":"projects/aets-mknkjs/agent/sessions/d55e1ae8-c5d3-1ecf-7d6a-9f27391b6b6c"}

Open in new window


But I extracted from Request.InputStream does not have double quotes.

{responseId:0b0b6903-60be-4fdf-919b-f20103bfd1ec-21947381,
queryResult:{queryText:I need to book a hotel room with queen size bed.,
parameters:{size:queen},
allRequiredParamsPresent:true,
fulfillmentMessages:[{text:{text:[]}}],intent:{name:projects/aets-mknkjs/agent/intents/1727505d-2499-42c4-95ec-7385b5da17a3,displayName:hotelbooking},intentDetectionConfidence:0.7410408,languageCode:en},originalDetectIntentRequest:{payload:{}},session:projects/aets-mknkjs/agent/sessions/d55e1ae8-c5d3-1ecf-7d6a-9f27391b6b6c}

Open in new window


How can I retain or extract the orginal message content?
0
Hi Experts!

I have been using DataSnap REST for some weeks but I have problems understanding some concepts related to TJSONObject and how these data are sent.
I have three related questions.
I consider a simple class:


TMyclass = class
  private
    [JSONName('name')] // invio
    Fname: string;
    [JSONName('surname')] // invio
    Fsurname: string;
    [JSONName('mytext')] // invio
    Fmytext: string;

    procedure Setname(const Value: string);
    procedure Setsurname(const Value: string);
    procedure Setmytext(const Value: string);
  public
    property name: string read Fname write Setname;
    property surname: string read Fsurname write Setsurname;
    property mytext: string read Fmytext write Setmytext;
  end;
  
.....

procedure TMyclass.Setname(const Value: string);
begin
  Fname := Value;
end;

procedure TMyclass.Setsurname(const Value: string);
begin
  Fsurname := Value;
end;

procedure TMyclass.Setmytext(const Value: string);
begin
  Fmytext := Value;
end;  

Open in new window


.....

In my code I have something similar to:

Procedure TMain.Send_JSON;
var
   VJSONObject: TJSONObject;
   VMyclass:TMyclass;
begin
   VMyclass:=TMyclass.Create;

   VMyclass.name:='John';
   VMyclass.surname:='Ace';
   VMyclass.mytext:='';

   VJSONObject:=TJson.ObjectToJsonObject(VMyclass);
   //...
   
   RESTClient1.ResetToDefaults;
   RESTRequest1.ResetToDefaults;
   RESTResponse1.ResetToDefaults;
   RESTClient1.BaseURL:='http://111.222.333.444:8080/datasnap/rest/mypath';
   RESTRequest1.Timeout:=RESTRequest_Timeout;
   
   RESTRequest1.Resource:='/MyParam'; 
   RESTRequest1.Method:=TRESTRequestMethod.rmPOST; 
   RESTRequest1.AddBody(VJSONObject.ToJSON, ContentTypeFromString('application/json'));
   //...
   RESTRequest1.Execute;
   //...
end;

Open in new window



[First question]
When I send this JSON:
         {"name":"John","surname":"Ace","mytext":""}
i don't want to have:
"mytext":""
in the JSON.

[Second question]
I don't know a way to insert a JSON array like this:
{"name":"John","file": [{"name_file":"myfile1.txt","dir_file":"C:\mydir"},{"name_file":"myfile2.txt","dir_file":"C:\mydir2"},...]}

[Third question]
I am looking for a method to manipulate the:

VJSONObject.ToString

before insert in the:

RESTRequest1.AddBody(VJSONObject.ToJSON,...

but I couldn't find it. I search something like:

  VJSONObject := Json.StringToJsonObject(VJSONObject.ToString);

I have a lot of problems because there is no documentation on this part.
Does anyone have a solution?


Working with RAD Studio Tokyo 10.2.3
0
I have working with an Rest api, which returns json data, but not sorted out the way I want. Api is not flexible enough, such that we can pass a sort parameter and it returns the result accordingly.

so, the data in such form

public class records {

....
      public Collection<Item> items ;

.....

}


in my c# code, I do something like this,


var results = CallApi();


var sortedResults = results.OrderBy(x => x.items.price);

return soretedResults.tolist();


I am concerned that this sorting and converting it back to the list , is expensive and as the results
grow larger, this might cause problem.

any thoughts in this?
0
I need to create dynamic Google Charts which gets the data from a DB stored procedure. I have managed to spit out the actual table with the function below.
var ajax = new XMLHttpRequest();
            var method = "GET";
            var url = "data.php";
            var asynchronous = true;
            ajax.open(method, url, asynchronous);

            //sending ajax request
            ajax.send();            

            // receiving response from data.php
            ajax.onreadystatechange = function()
            {
                if (this.readyState == 4 && this.status == 200)
                {
                    //converting JSON back to array
                    var dataTable = JSON.parse(this.responseText);
                    console.log(dataTable); // for debugging

                    // html value for <tbody>
                    var html = "";
                    // looping through the data
                    for (var a = 0; a < dataTable.length; a++)
                    {
                        var categoryValue = dataTable[a].Category;
                        var monthJan = dataTable[a].Month1;
                        var monthFeb = dataTable[a].Month2;
                        var monthMar = dataTable[a].Month3;
                        var monthApr = dataTable[a].Month4;
                        var monthMay = dataTable[a].Month5;


                        // appending at HTML
                        html += "<tr>";
                        html += 

Open in new window

0
I am attempting to scrape the following URL:

https://www.oddsportal.com/soccer/england/premier-league/liverpool-norwich-4IMoMG3q/

Using the Network tab in Chrome's developer tools, you can see there is an API that feeds the data into the website - which is in the form of a JSON - and looks as below. This data is what I am trying to scrape.

https://fb.oddsportal.com/feed/match/1-1-4IMoMG3q-5-2-yj1e3.dat?_=1562831112277

This is the code I am currently trying to scrape this with:

from selenium.webdriver.chrome.options import Options
import json
import urllib.parse
from time import time

options = Options()
options.headless = True
driver = webdriver.Chrome(options=options)

# Access the initial webpage to create the info_dict (including the match_id, and hash)
driver.get('https://www.oddsportal.com/soccer/england/premier-league/liverpool-norwich-4IMoMG3q')
page = driver.page_source
info_dict = json.loads(page.split('var page = new PageEvent(')[-1].split(');')[0])
xhash = urllib.parse.unquote(info_dict['xhash'])
match_id = info_dict['id']

# Access to the feed URL based on the values from the info_dict
driver.get('http://fb.oddsportal.com/feed/match/1-1-{}-1-2-{}.dat?_={}'.format(match_id, xhash, int(round(time()*1000)) + 1000))
print(driver.page_source)

Open in new window


The URL is built up of 3 factors - the match_id, the hash, and epoch time in milliseconds. However, when I try to access this in Selenium, I get the following response:

globals.jsonpCallback('/feed/match/1-1-4IMoMG3q-1-2-yjb3a.dat?_=1562795864899', {'e':'404'})

Open in new window


Would really appreciate any help with this, as I don't really understand where I'm going wrong!
0
CompTIA Cloud+
LVL 13
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Hi Experts,
 We are working on Azure POC for Platform as Service and IAAS. We have created the resources as per the attached architecture.  Now we have to download those resources and working on Infrastructure as code.

I have exported template from Resource group. Now we are planning to create the same environment by this template to another tenant. I have tried to download and deploy template to another tenant but did not work out. Do i need to change any parameter?

Can you please advice me for the steps?

Thank you
Architecture.pptx
ExportedTemplate-Magnificent_8.zip
0
I am using C3.js to show a graph whose data is coming from a URL that is returning JSON formatted data.
Everything works like a charm except when I want to show a simple "No Data Available" when data is empty.

Reading C3 documentation the solution seems to be pretty easy and has to be added within the data array:
empty: {
    label: {
        text: "No Data Available"
    }
},

Open in new window


This is not working "completely" since the text informing of no data available is showing for a fraction of a second and disappear immediately.

I was not able to find any clue showing me a behavior like this.

Just for the records I am using last versions:
 - C3.js 0.7.1
 - D3.js 5.9.2
and of course the related C3.css

Any suggestion?
0
I installed Guzzle and  the Avalara tax client on my machine today and got the attached notices while doing so... is that "hard copies" notice something to be concerned about? It seems like its saying that it took a snapshot of those folders and if I ever change anything in the source folders from now on I need to reinstall, which obviously isn't good.
2019-06-14_13-03-46.jpg
0
MSSQL query to JSON

i have these 2 queries that i need to combine into a single record set then convert to a JSON object, i am afraid i know nothing about how to do this,
   EXEC	[dbo].[YearCompGraph] '2018/01/01', '2018/12/31',2 
   EXEC	[dbo].[YearCompGraph] '2019/01/01', '2019/12/31',2

Open in new window

the stored proc
USE [cmms]
GO
/****** Object:  StoredProcedure [dbo].[YearCompGraph]    Script Date: 11/06/2019 17:45:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Duong Ba Hong Minh, minhdbh
-- Create date: 2012/02/12
-- Description:	Insert new tree Node
-- If Parent_ID =0 or null: Node is root
-- =============================================
ALTER PROCEDURE [dbo].[YearCompGraph]
	
	@1stDate date,
	@2ndDate date,
	@eqpID int
AS
BEGIN
	
	SET NOCOUNT ON;
SELECT SUM(CASE datepart(month,ReqDate) WHEN 1 THEN 1 ELSE 0 END) AS 'January',
  SUM(CASE datepart(month,ReqDate) WHEN 2 THEN 1 ELSE 0 END) AS 'February',
  SUM(CASE datepart(month,ReqDate) WHEN 3 THEN 1 ELSE 0 END) AS 'March',
  SUM(CASE datepart(month,ReqDate) WHEN 4 THEN 1 ELSE 0 END) AS 'April',
  SUM(CASE datepart(month,ReqDate) WHEN 5 THEN 1 ELSE 0 END) AS 'May',
  SUM(CASE datepart(month,ReqDate) WHEN 6 THEN 1 ELSE 0 END) AS 'June',
  SUM(CASE datepart(month,ReqDate) WHEN 7 THEN 1 ELSE 0 END) AS 'July',
  SUM(CASE datepart(month,ReqDate) WHEN 8 THEN 1 ELSE 0 END) AS 'August',
  SUM(CASE datepart(month,ReqDate) WHEN 9 THEN 1 ELSE 0 

Open in new window

0
I'm trying to parse out a JSON array response from a 3rd party API, and am having difficulties. My json is:

let jsonResponse = 
{  
   "errors":[  
      {  
         "code":"PMT-4000",
         "type":"invalid_request",
         "message":"card.number is invalid.",
         "detail":"card.number",
         "infoLink":"https://developer.intuit.com/v2/docs?redirectID=PayErrors"
      }
   ]
}

Open in new window


seeing how it's a json array, I thought I could access each field like:

console.write( jsonResponse.errors[ 0 ].message );

but i keep getting a message saying it's undefined.
0
I need a way of pulling car trade-in values from kbb.com or some other source into this Google spreadsheet https://docs.google.com/spreadsheets/d/19x5gqcy-9CCaoguq5aFOlY-W1P7H6HaqYxjp3PQLoAM/edit#gid=288072689.
0

JSON

960

Solutions

900

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.