JSON

480

Solutions

6

Articles & Videos

521

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

Hello,
  I am using swagger - YAML and I need some help on how to define  a json response object


Here is the JSON:

{
    "keywords": [],
    "distance": "25",
    "jobType": "all",
    "sectorId": "0",
    "location": {
        "lat": "33.7489954",
        "lng": "-84.3879824",
        "name": "Atlanta, GA"
    }
}

please note the keywords can be an empty array [] or have value like ['a','b','c']

Thanks for your help
0
Turn Insights into Action
Turn Insights into Action

Communication across every corner of your business is essential to increase the velocity of your application delivery and support pipeline. Automate, standardize, and contextualize your communication processes with xMatters.

Hello nodejs experts

Is there is anything more on node js standards?  


All urls must be in lower case

Ex: /notification/sendotp

Use HTTP verbs (GET, POST, PUT, DELETE) to operate on the collections and elements.

Use GET – for retrieving single or list data

Use POST – for create data

Use PUT – for update data

Use DELETE – for delete data

HTTP METHOD

POST

GET

PUT

DELETE

CRUD OP

CREATE

READ

UPDATE

DELETE


URLs should include nouns, not verbs in API names. Avoid get,update,save, delete, list in API names.

Maintain singular and plural nouns for APIs.

Ex: for single image retrive – GET - /user/image

For list of images – GET – user/images

User Token must be in headers only. Not as path param or in json body

Use resource, sub-resources for relations

Ex: for user videos use - /user/videos

Put the version number at the base of your URL. /v1/user/images

Controller will have only mandatory parameter validations and sending success, error responses no business logic. Use Service and Helper files for business logic. DAO for db calls

Handle Errors with HTTP status codes

200 – OK – Everything is fine. Created, Saved, Data found

400 – Validations Failed, Missing Mandatory Params, No data found, User already exists, already voted, in valid comment, comment not allowed within a hour, invalid user, invalid video, Video not found

500 – Unknown error, Database error, ES down, timeout from third-party. …
0
I am trying to create a Json object in C# that I will convert to XML.   I have a repeating set of Fees that I need to add to the json object.

Here is my code so far:

root.Deal.Fees = new ExpandoObject();
List<ExpandoObject> feeArray = new List<ExpandoObject>();

foreach (DataRow ro in ds.Tables["fees"].Rows)
{
    root.Deal.Fees.DealFees.Fee.Description = ro["fee_type"].ToString();;
    root.Deal.Fees.DealFees.Fee.Amount = ro["amount"].ToString();

feeArray.Add(root.Deal.Fees);
}

Open in new window


No sure what else is needed.   Supply a different example if that is easier for you.
Thank you
0
I am trying to run json linq query in Visual Studio 2008. I am getting the error :

select is not a member of newtonsoft.json.linq.array

Below is my code

Dim APIURL As String = "https://mydomain/api/v1/enrollments/search?id=12345"
            Dim req As WebRequest = WebRequest.Create(APIURL)
            req.ContentType = "application/json; charset=utf-8"
            req.Credentials = New System.Net.NetworkCredential("xyz", "123")
            req.Method = WebRequestMethods.Http.Get

            Dim text As String = ""
            Dim dt As DataTable = New DataTable
            Dim res As Stream = req.GetResponse().GetResponseStream
            Dim reader As New StreamReader(res)
            Dim response As String = reader.ReadToEnd()

            reader.Close()
            res.Close()

              Dim parsedObject = JObject.Parse(response)

            Dim docs = JArray.FromObject(parsedObject("enrollments")).Select(Function(x) x.ToObject(Of jSonClass.Enrollment)()) 'Error here
EE_json.txt
0
http://maps.aerophotos.cf/test.
Basically make the markers update every second or so from the JSON file aswell as display the data in the JSON file i.e altitude callsign etc when clicking on marker.
0
I am trying to get a json to vb.net class.
I have used the Visual studio converter for this and generated the class, but it is not working.
 The commented   ' Public Property Wlisting() As WooData does not work,
I have tried different methods of calling an array or a list but always get the same error.  The Json that come over appears correctly formed, it is the inability to get it into a class which is the problem.

The line :

  Dim WooResponse = JsonConvert.DeserializeObject(Of WooCommerceData.Results)(result)

gives the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Zetsy.WooCommerceData.Results' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

Zit appears I should be calling this as a differnt type of list, but what I have tried gives the same error
=========================================================================


The class is the following:

Namespace WooCommerceData
    Public Class Results
        Public Property Wlistings As List(Of WooData)
        ' Public …
0
How to populate select options from database in jquery. I am using datatables editor plugin to edit the row.

var local_path = "/dashboardlocal_list/0/?format=json";
var local_editor = new $.fn.dataTable.Editor( {
        idSrc:  'id',
        ajax: {
            // create: {
            //     type: 'POST',
            //     url:  '/dashboard/local_detail/'+ idSrc +'/?format=api'
            // },
            edit: {
                type: 'PUT',
                url:  '/dashboard/local_detail/_id_/',
                data: function (d) {
                        var updated_data = {};
                        $.each( d.data, function (id, value) {
                            updated_data['description'] = value['description'];
                            updated_data['start_date'] = value['start_date'];
                            updated_data['end_date'] = value['end_date'];
                            updated_data['task.name'] = value['task.name'];
                                                             } );
                        console.log(updated_data);
                        return updated_data;
                                 },

                success: function() {
                        console.log('Updated')
                        workorder_table.api().ajax.reload();
                                    },
                    },
            remove: {
                type: 'DELETE',
                url:  …
0
Hye experts, i have a problem to display data in data datagrid based on searching..can someone look it up..
Thank you for your help

Here is my code: test3.php

<?php
include "utama.php";
?>

<script type="text/javascript">
 function doSearch(){
    $('#tt').datagrid('load',{
        MUKIM: $('#mukim').val()
    });
}
</script>




<table id="tt" class="easyui-datagrid" style="width:600px;height:250px"
        url="test4.php" toolbar="#tb"
        title="Load Data" iconCls="icon-save"
        rownumbers="true" pagination="true">
    <thead>
        <tr>
            <th field="MUKIM" width="80">MUKIM</th>
            <th field="KAWASAN" width="80">KAWASAN</th>
            <th field="NAMA_KAWASAN" width="80" align="right">NAMA_KAWASAN</th>
        </tr>
    </thead>
</table>

<div id="tb" style="padding:3px">
    <div>
    <input name="MUKIM" id="mukim" class="easyui-combobox" style="width:100%"
            data-options= "label: 'MUKIM : ',
            valueField: 'MUKIM',
            textField: 'NAMA_MUKIM',
            url: 'dropdown_mukim.php'">
    </div>
    <a href="#" class="easyui-linkbutton" plain="true" onclick="doSearch()">Search</a>
</div>

code test4.php

<?php
include "connection.php";
$mukim = isset($_POST['mukim']);


if (isset( $_POST ["mukim"] ))
{
    $mukim = $_POST ["mukim"];
}

// echo  $name ;
// echo $phone;
// echo $mukim;

$rs = $conn->prepare("SELECT KAWASAN, NAMA_KAWASAN, MUKIM FROM …
0
Hello,

i have a class that I am using JSON to read the data from. I am getting this error but not quite sure why when I am not seeing an array in my class

ERROR
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[SpringAhead.Timecard]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path '?xml', line 1, position 8.

Open in new window



CLASS
Imports System.Xml.Serialization
''' <remarks/>
<System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")>
<System.SerializableAttribute>
<System.Diagnostics.DebuggerStepThroughAttribute>
<System.ComponentModel.DesignerCategoryAttribute("code")>
<System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=True)>
Partial Public Class SA

    Private timecardField As Timecard()

    ''' <remarks/>
    <System.Xml.Serialization.XmlElementAttribute("Timecard", IsNullable:=True)>
    Public Property Timecard() As Timecard()
  

Open in new window

0
I am having array of json object in java script and want to iterate in jsp.
we are using struts 1.1 kindly help.
0
Free Tool: Site Down Detector
LVL 9
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

I am using a JavaScript plugin called listjs.  For those that don't know about it, what it does is the following.
You configure a textbox as a search and then tag columns in a table with class names and use those names to configure the options on the listjs plugin.

The plugin will then rebuild your list allowing incremental search returns of rows have strings which match the search box values.  It mostly works, but with a hidden string which is a JSON structure it only partially works,  I can find matches for say  8 rows and when I add another character that still matches in order the 8 rows,  one or more rows disappears.

Also,  in jQuery,  I set the val() of the searchbox to what should return some rows, and it behaves as though nothing was entered.  It seems that it knows about keypress and using jQuery to plop the value in has no keypress.

Any advice on these issues would be greatlya appreciated.

Thanks.
0
Dear Experts, I'mt rying to use GO to read a json file that I have.

I'm using the following code:
package main

import (
	"fmt"
	"encoding/json"
	"io/ioutil"
)

func main() {

	b, _ := ioutil.ReadFile("/home/david/jsontest/create.jsontest.campaigns.ninja.json")

	type UserData struct {
		user_id    string
		user_email string
		user_name  string
	}

	type campaign struct {
		domain      string
		Ssl         int64
		server_key  string
		certificate string
		bundle      string
		php_ver     string
		wp          int64
		lang        string
		start_date  string
		end_date    string
		description string
		user_data   UserData
		CampaignID  int64
	}

	var m campaign
	err := json.Unmarshal(b, &m)
	if err != nil {
		panic (err)
	}
	fmt.Printf("%d", m.CampaignID)
	fmt.Printf("%s",m.user_data.user_email)
}

Open in new window


When I run the code however, the Result is this:
/usr/lib/golang/bin/go run /home/david/GoglandProjects/CampaignsNinja/jsontest.go
80099700
Process finished with exit code 0

Which is correct, but partial.. I'm missing the 2nd value which should be 74 (according to the  attached JSON below)

{"domain":"jsontest.campaigns.ninja","ssl":1,"server_key":"","certificate":"","bundle":"","php_ver":"5.6","wp":1,"lang":"english","start_date":"2017-02-02","end_date":"2017-03-02","description":"This is a test","user_data":{"user_id":"74","user_email":"usertest@gmail.com","user_name":"usertest"},"CampaignID":80099700}

Any Ideas why is the code behaving that way?
0
Hi guys,

I'm very new to Go and I'm afraif the guides regarding JSON aren't very clear.

I have the following JSON output (saved as a .json file in a certain path) the content of which is

{"domain":"jsontest.campaigns.ninja","ssl":1,"server_key":"","certificate":"","bundle":"","php_ver":"5.6","wp":1,"lang":"english","start_date":"2017-02-02","end_date":"2017-03-02","description":"This is a test","user_data":{"user_id":"74","user_email":"usertest@gmail.com","user_name":"usertest"},"CampaignID":80099700}

and the following Piece of code written in Go:

package main

import (
	"io/ioutil"
	"log"
	"strings"
	"encoding/json"
	"os"
)

func main() {
	type Message struct {
		domain      string
		ssl         int
		server_key  string
		certificate string
		bundle      string
		php_ver     string
		wp          int
		lang        string
		start_date  string
		end_date    string
		Description string
	}

	var m Message
	err := json.Unmarshal(b, &m)
}

Open in new window


Where b should be the path to the json file.

but as you can see, the JSON itswelf has nested fields...

My question is,
and I'm sorry if it's a long one but I really tried looking it up just can't get the concept...
How do I include the nested fields in the structure called Message and how do I read each and every value into a variable (preferably not an array but a separate variable for each value)
0
Hello guys, I'm editing a file so I can get a chart as the team needs, but I actually don't know Json or JS. Can anybody hepl ?

This is the code for the plot I have today:


	var seriesTitle = [['0 - 5 days'],['6 - 10 days'],['11 - 20 days'],['21 - 30 days'],['31 - 60 days'],['61 - 90 days'],['More than 90 days']];
	
  plot3 = $.jqplot('chart3', [[sla_5],[sla_10],[sla_20],[sla_30],[sla_60],[sla_90],[sla_plus]], {
	title: '<b>Aging Incidents per Categories',

    // Tell the plot to stack the bars.
    stackSeries: false,
	seriesColors:['#0ba500', '#659ed3','#f4eb02','#e2b01b','#d17b63','#8b4513','#e2251b'],
    captureRightClick: true,
    seriesDefaults:{
      renderer:$.jqplot.BarRenderer,
	  label:[['sla_5'],['sla_10'],['sla_20'],['sla_30'],['sla_60'],['sla_90'],['sla_plus']],
      rendererOptions: {
        //   Put a 30 pixel margin between bars.
          barMargin: 40,
        //   Highlight bars when mouse button pressed.
        //   Disables default highlighting on mouse over.
          highlightMouseDown:false , 
		  barDirection: 'vertical'
      },
      pointLabels: {
		  show: true,
		  color: 'white',
		  hideZeros: true,
		  FontColor : "#FFFFFF"
	  }
    },

	series:[
            {label:'0 - 5 days - Total ' + sla_total[0]},
            {label:'6 - 10 days - Total ' + sla_total[1]},
            {label:'11 - 20 days - Total ' + sla_total[2]},
			{label:'21 - 30 days - Total ' + sla_total[3]},
			{label:'31 - 60 days - Total ' + sla_total[4]},
	

Open in new window

0
I am having a very complex string that I need to tokenize and also create name pair values when possible. Here is a sample of the strings I have

Recod Style 1
Search Result Queries;SomeHotel.com;PT\=89030726\;PA\=-1119567914\;PS\=1547518063;2017-05-13 01:43:36.719;Search Results Query BT SPLIT=checkInDate\=5-13-2017&checkOutDate\=5-14-2017&numberOfAdults\=1&propertyIds\=MS140|MS741|MS1290|MS1334|MS1349|MS4557|MS4568|MS4783|MS4854|SS6029,Web Requests - Client IP=50.251.11.233;Execution Time Informix=2404.003662109375,DB Count=2.0,DB Time=2404.0037887319922;false;;2424.760498046875;2424.760498046875;8.655830353498459;2424.7605440989137;;;;SomeHotel_PROD;dyntrc-mgmt.SomeHotel.com


Recod Style 2
Search Result Queries;Mobile App;PT\=89031695\;PA\=-1119567914\;PS\=1547518063;2017-05-13 01:44:17.772;Search Results Query BT SPLIT=checkInDate\=5-13-2017&checkOutDate\=5-14-2017&corporatePlusNumber\=&numberOfAdults\=1&propertyIds\=MS1173%7CMS4961%7CMS4376%7CMS4281,Web Requests - Client IP=66.115.209.42;Execution Time Informix=1762.662109375,DB Count=5.0,DB Time=1759.847623437643;false;;1781.0732421875;1781.0732421875;10.074070394039154;1781.0732627734542;;;;SomeHotel_PROD;dyntrc-mgmt.SomeHotel.com

Both record styles happen in the same file.

Main delimiter above is;
some values are name-value pairs delimited on \= or =
Some fields contain other fields and delimited by &

Any ideas on how to parse this so I can convert it to some CSV or json
0
I am error trapping a json call error in .NET.

Documentation says this would be the response on error:

Error Response      Code: 401 Unauthorized
Content: {"connection":"Error","message":"Please check the following; a) the credentials you have provided are correct, b) the IP address you are requesting from is authorised, c) your account is not suspended."}


Question is I can see the Code: 401 Unauthorized error but cannot get the content (a,b,c) with the details of what happen to cause the auth error.

Can this be done in .NET?
0
we are generating dynamic controls like dropdown and textboxes so how we need to get data and assign those values to array and creating query string and pass that to one variale using ajax
please let me know the answer for this question
dyn_html.php
0
Hi Experts,

I'm in need of a powershell that can output to a JSON file the size of our SQL log files.

We have multiple SQL servers and we have lots of problems with transaction logs growing to ridiculous sizes so I'm hoping there is a way I can report back to save me logging onto each server every day!  

Firstly is this possible, secondly how would I go about writing the powershell?

please let me know if you need more information

thanks in advance for your help
0
I have two sharepoint lists that are identical structurally (only difference is data) now I want to be able to query both list and consolidated the returned values.
Very new at javascrit and Angular but I've attempted to just duplicate my first query and I seem to be getting output from both lists but cannot figure out how to consolidate into one.

see code below.

(function () {
  'use strict';

  angular
    .module('myApp.core')
    .controller('DefaultController', DefaultController);

  DefaultController.$inject = ["SharePointService"];

  function DefaultController(SharePointService) {

    var vm = this;






    vm.search = function () {


        SharePointService.getWithFilter('ExpectationsList1', "?$select=Id,DocTitle,ParaNum,SentText&$filter=substringof('" + vm.query + "', SentText) eq true").then(function (response1) {
 
                //vm.expectations = response1

                console.log(response1);

        });
        SharePointService.getWithFilter('ExpectationsList2', "?$select=Id,DocTitle,ParaNum,SentText&$filter=substringof('" + vm.query + "', SentText) eq true").then(function (response2) {

            //vm.expectations = response2


			console.log(response2)			

        });


        

    }


  }

})();

Open in new window

0
Raise the IQ of Your IT Alerts
Raise the IQ of Your IT Alerts

From IT major incidents to manufacturing line slowdowns, every business process generates insights that need to reach the people required to take action. You need a platform that integrates with your business tools to create fully enabled DevOps toolchains.

You need xMatters.

I have a python snippet that dumps the json data from a command.

I am trying to retrieve specific key value and assign to variables but not returning anything.  Any thoughts?

Raw data:
/usr/bin/sudo pm2 jlist

Open in new window

0
I have an SQL database which has a table with a JSON string column.  I need to attach it to an Excel database and convert the JSON string to something more readable.

I can connect to the database and get back either a view (the preferred data source) or the underlying table.  I would like to take the query that built excel view and modify the JSON column to be more user friendly.

I guess the first question is how to get to the SQL to modify it.  I don't see any show SQL commands in Excel.
0
I'm just trying to find the right syntax to use to set the background color of a node in json with google charts.

This is the code I have and of course it's not working because I have no idea what I'm doing.

	
$style = new stdClass;
$style->p = "style: 'background-color:green;'";
$item->p = $style;

Open in new window


There's more to my code of course but this is what I'm using to set the background color of a specific node.
0
I'm new to the android development. I have created an android qr-code scanner app using using Zxing Library.Now I have to send the qr data to a remote database and retrieve result and display inside the app.Kind of checking status and display the results from remote database against the qr-value. If data not present in database then it will show some text.

Suppose you have a qr-code and its value is 1234567890.Now after scanning through the scanner the value will be sent to the remote server automatically.It will check and return data will be displayed as given below.

Status: OK

Name: Alexander Pierce

ID: STU986734

DOB: 7/4/90

Father: John Price

Mother: Nadia Price

Address: 33 West 60th St.,New York, NY 10023

I know it can be done with JSON Parsing. I googled but unable to find proper tutorial for my existing QR scanner app code. So if anyone can show me step by step for server/database side script and android side code,it will be very helpful for my project. I have the mySQL database with all the details we need.

Any suggestion would be greatly appreciated. Thank you all.

QR Scanner App: (HomActivity.java)
package in.debo.android_qrcode_scanner_bulk_scan_with_flash;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import 

Open in new window

0
I need to provide a JSON feed that looks like this:
{"redirect_flows": {
    "description": "Wine boxes",
    "session_token": "SESS_wSs0uGYMISxzqOBq",
    "success_redirect_url": "https://example.com/pay/confirm", "prefilled_customers": { "email":"emailaddress","given_name":"firstname","family_name":"lastname","address_line1":"address1 Road","address_line2":null,"city":"London","postal_code":"postcode","country_code":"GB" },  "links": { "creditor": "CR123" }}}

I've been using the JavaScriptSerializer to serialize the data   in a similar BUT simpler JSON feed and using replace to tweak the feed to go from this:
[{"email":"emailaddress","given_name":"firstname","family_name":"lastname","address_line1":"address1 Road","address_line2":null,"city":"London","postal_code":"postcode","country_code":"GB")]
to this:
{ "customers" : { "email":"emailaddress","given_name":"firstname","family_name":"lastname","address_line1":"address1 Road","address_line2":null,"city":"London","postal_code":"postcode","country_code":"GB", "metadata": {"customerid":"124"}}}

Can someone help me and show me how I can add the metadata  programmatically and more importantly scalable so I don't have to use the replace etc. every time?

Thanks

Mark
0
Hello,
I've just started learning python on my own and I am having trouble with creating a visualization of json data.  Basically, I am pulling data from the Kepler mission which consists of confirmed planetary systems.  For example, When I run the program, I generate a file called gcolumn.js which contains the following data. The first column contains the kepler designation of the host star while the second column contains the number of confirmed planets that are orbiting it.
['Kepler-102 ',5]
['Kepler-11 ',6]
['Kepler-122 ',5]
['Kepler-292 ',5]
['Kepler-296 ',5]
['Kepler-33 ',5]
['Kepler-444 ',5]
['Kepler-62 ',5]
['Kepler-80 ',5]
['Kepler-90 ',6]

What I want to do is create a google column chart with the kepler designations on the x axis and the number of planets orbiting a star on the Y axis.  I chose this in order to start with something simple. I've gone ahead and modified the code from google charts so that it would pull the data for gcolumn.js (that is the data from above.  Below I have pasted a copy of htm file that contains the visualization code. When I run gcolumn.py, it generate gcolumn.js which is then accessed by gcolumn.htm which is shown below. However when I run everything, the column chart does not appear.  Thanks
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript" src="gcolumn.js">
    google.charts.load("current", {packages:['corechart']});
    

Open in new window

0

JSON

480

Solutions

6

Articles & Videos

521

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