[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x

JSON

547

Solutions

573

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,

The question below was generated by needing to document a JSON structure, but I suppose it could apply to other data formats as well.

Suppose I have a structure:
{
   name: "John Doe",
   address: "1234 Main Street",
   vitals: {
       hair_color: "brown",
       eyes: "blue",
    },
   DOB: "01-01-2000",
   sex: "Male"  
}

Normally, I'd create a table with one row per data element. But, then I have the vitals block, which contains two data elements. Should I create a separate table for vitals, even though it contains only two fields? And reference it in the main table?

Thanks,
Steve
0
Free Tool: SSL Checker
LVL 10
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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.

Hello Support

The attached download enables the ability to convert JSON file format to HCL format (which is developed by a company called Hashicorp.

There is a readme included in the download to describe how to carry out the conversion. However, the demonstration shows how to carry out the conversion in Linux. Unfortunately, I don't know Linux. Therefore, I was wondering if someone could show me how to carryout the conversion in Windows? If not, if someone to talk me through in simple terms how to carry out the conversion in Linux that would also be great - but as I mentioned I'm not a Linux person.

Your assistance will be greatly appreciated.

Cheers

Carlton
0
I don't understand why I get undefined below.

var index = -1;
var proj = "893x-3owe34p";

alert(getIndex(proj));
function getIndex(val){
var filteredObj = jsonFile.Result.Contracts.find(function(item, i) {
  //console.log(item.Plan.Identification.PlanNumber)
  if (item.Plan.Identification.PlanNumber == val) {
    index = i;
    return index;
  }
  //return index;
});

  }

Open in new window


https://jsfiddle.net/isogunro/681j6nk6/1/
0
How can I retrieve the index of a JSON array?  In my json, there's a PlanNumber with a value and I need to retrieve the index.  The Json in my fiddle show 5 contracts and each having a plan number.

Not working for me.
var index = -1;
var val = "8930-3o3pp";
var filteredObj = jsonFile.Result.Contracts.find(function(item, i){
  if(item.Plan.PlanNumber === val){
    index = i;
    return i;
  }
});

alert(index, filteredObj);

Open in new window

https://jsfiddle.net/isogunro/z6f33doy/3/
0
Hi All,

I am trying to do some things with JSON that I have coded in jsfiddle.  When "PROJ123" is entered into the "Project Number" field, the "Plan Number" drop down box gets populated with corresponding values.  When it gets populated though, I want the default value to be blank.  How do I do that?

Also, I want the corresponding contract type to populate <span id="contractType"></span> based on the "Plan Number" selected.
Here's how to get the contract type Contracts[x].Plan.Info.ContractType from JSON.

<table border="1" width="65%" style="background-color:#eeeeee">
  <tr style="background-color:#00558D;color:white;font-weight:bold;font-size:14px">
    <td colspan="4">New Contract</td>
  </tr>

  <tr>
  	<td>Project Number</td>
  	<td colspan="3"><input type="text" value="" id="projectNumber"></td>
  </tr>

  <tr>
  	<td>Plan Number</td>
  	<td colspan="3">
  		<select id="planNumber">
  			<option value=""></option>
  		</select><span id="contractType"></span>
  	</td>
  </tr>

Open in new window



function getPlanNumbers(projNumber){
$("#planNumber").empty();

var planNumber = [];
var y=0;
var pNumOption = document.getElementById("planNumber");

for (var x=0; x<jsonFile.Result.Contracts.length; x++){
//alert(jsonFile.Result.Contracts[x].Plan.Info.ProjectNumber);
if (jsonFile.Result.Contracts[x].Plan.Info.ProjectNumber === projNumber){
planNumber.push(jsonFile.Result.Contracts[x].Plan.Identification.PlanNumber);
}else{
y++;
}
}
if (jsonFile.Result.Contracts.length == y){
alert("Project Number '"+ projNumber + "' does not exist.");
}else{
for(var i=0; i<planNumber.length; i++){
var option = document.createElement('option');
                                
option.value = planNumber[i];
option.innerHTML = planNumber[i];
                                   
pNumOption.appendChild(option);
}

}

// alert("populate dropdown");
}

Open in new window


The actual JSON can be found at this jsfiddle with the rest of the code.
https://jsfiddle.net/isogunro/03y6zwbe/
0
My jQuery autocomplete works for the IP Address listed here http://45.33.62.115/rates/index2.php

However it does not work for the server address here https://consolidatedutilities.com/rates/index2.php
0
I need some help w/ jquery validate plugin - here is the jsfiddle:

 https://jsfiddle.net/damon_matt/ughvc0ak/

My use case is to make sure the user has selected from the drop down, filled out the 2 text boxes (Number & Book Name), do a remote call for value entered in Book Name, which will return a json object like so: [{"success": false, "IsDuplicate":true}] - in this case, since the "IsDuplicate" is true, it means that the book name already exists in the database and user has to be prompted that a different name has to be entered.

Once all the validations are successfully completed, then the "targetDiv" div has to be set to displayed (which is currently hidden). All these validations need to be done onBlur or something similar to this:

https://jqueryvalidation.org/files/demo/

 I've searched extensively to find a working jsfiddle but have not been able to find anything that works for me. Can my use case be achieved via jquery validate plugin, or, do I need to build custom validation?
0
I have a jQuery autocomplete where it is populated a JSON file with a label and a value.

Can someone write a event handler in my script that will call a function and alert the value when it is selected from the autocomplete?

$(document).ready(function() {
    $('#rates-input').autocomplete({
        source: "../js/selections.php"
    });
});

Open in new window

0
Anybody know why the onchange() isn't working?  This is the error I get
Uncaught ReferenceError: getProj is not defined
    at HTMLSelectElement.onchange


http://jsfiddle.net/isogunro/r6e4gm34/

<select id="contracts" onchange="getProj(this)">
  <option value=""></option>
</select>
<span id="ctType"></span>


function getProj(sel) {
var ct = document.getElementById("ctType");
ct.innerHTML = contractAry[2].contractType;
	alert(sel.value);
  
}

Open in new window

0
HI experts,
could you suggest few products which can create stunning colorful and appealing UI design for Web and possible for IPad and Mobile.
 Which can read json msg and render UI.

Please advise

Similiar to below
https://www.awwwards.com/creative-ui-design-examples-for-great-ux.html

https://www.behance.net/gallery/4146415/MINIMETEO-for-iPad

https://dribbble.com/shots/606745-In-app-Visual-Data
0
Free Tool: IP Lookup
LVL 10
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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 have a series of pictures and I would like to convert it to a json file so I can use it in an app.
How would I convert or make these as json file
0
Hello All,

I get the following error as I try to read a certain node from the json below.  This alert gives the highlighted error:
alert(jsonFile.Result.Contracts[0].Modifications.Info.VendorBusinessType);

"Cannot read property 'VendorBusinessType' of undefined"

{
  "Result": {
    "Contracts": [
      {
        "Scope": {
          "Identification": {
            "PlanNumber": "8930-3o3pp"
          },
          "Info": {
            "Title": "chjdj",
            "ProjectNumber": "PROJ123",
            "StationCode": "STATIONCD1",
            "ContractType": "Commodities",
            "ActionType": "chvj-PLAN"
          },
          "Dates": {},
          "Financial": {
            "PlannedFunding": 20000
          },
          "Status": {
            "PlanStatus": "Draft",
            "DateOfLastPlanStatusChange": "/Date(1393887495760-0000)/"
          }
        },
        "Solicit": {
          "Identification": {
            "SolicitationNumber": "svzst-11-Q-xxx"
          },
          "Info": {
            "Title": "vchdsxx",
            "ProjectNumber": "PROJ123",
            "StationCode": "STATIONCD1",
            "ContractType": "Architecture/Engineering – Minor",
            "ActionType": "FSS-RFQ"
          },
          "Dates": {
            "DateIssued": "/Date(1393826400000-0000)/" /*Mon Mar 03 2014 01:00:00 GMT-0500 (Eastern Standard Time)*/,
            "ResponseDueDate": "/Date(1394427600000-0000)/"
           /*Mon Mar 10 2014 01:00:00

Open in new window

0
I've got a problem that needs solving and it involves the function that you see below. I'm trying to get to a place where I can understand every line of the code and I would appreciate some confirmation on what I THINK I understand. In other instances, I'm just plain stuck.

Here's what I've got:

    function filterInit(){ // Init means I'm starting this as soon as the page initializes
        $('select').material_select(); // I don't know what "material_select" means

        $.ajax({ //this is what's happening when the user clicks on the "select" - you've got an AJAX request being triggered
            'url': '/admin/library/get-tags', // the URL of the code that's returning data
            'data': {
                'filtered': true // don't know what the significance of this is
            },
            'dataType': 'JSON', // data type is JSON
            'success': function(resp){ // if there's data being returned, then do the following
                // remove everything but the default option since it acts as the label for material_select()
                $('#filter-tags option:not([value=""])').remove(); // if the value is blank, remove it
                $('#filter-tags-default option:not([value=""])').remove(); //if the value is blank, remove it

                // add the tags as options
                for (var i in resp.data) { //populating the select with options, but I don't understand the next two lines
                    var $select …
0
Hello,

I was given an API by my client and as I was working with the API (several weeks), I notice that sometimes a node that was there before wouldn't be there at another time.  
For example, "widget.window.title" could be missing next week.

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": { 
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}  

Open in new window




How can I check if a node exist using javaScript before attempting to use it?
0
CheckBox[] boxes = new CheckBox[6];
            boxes[0] = checkBox1;
            boxes[1] = checkBox2;
            boxes[2] = checkBox3;
            boxes[3] = checkBox4;
            boxes[4] = checkBox5;
            boxes[5] = checkBox6;
            // C#
            // Set to details view.
            listView1.View = View.Details;
            // Add a column with width 20 and left alignment.
            listView1.Columns.Add("Instrument", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Bid", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Ask", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Last Price", 65, HorizontalAlignment.Left);

            string bal = RetrieveAccountBalance();

            var y = JsonConvert.DeserializeObject<List<AccountDetail>>(bal);

            for (var i = 0;i <= 6; i++)
            {

                 if (boxes[i].Checked)
                {
                    var s = boxes[i].Tag;

                    string x = "/market/" + s +"/AUD/tick";
                    string o = GetMarketTick(x); //{"bestBid":354.0,"bestAsk":356.89,"lastPrice":356.99,"currency":"AUD","instrument":"ETH","timestamp":1506254860,"volume24h":1183.241}

                    var h = JsonConvert.DeserializeObject<List<TickDetail>>(o);
                    for (var z = 0; z < h.Count; z++)
                    {
                        string[] row = { h[z].instrument, h[z].bestBid, h[z].bestAsk, h[z].lastPrice };
 

Open in new window

0
Hello Experts

I am getting a json response from a URL which I am trying parse it and capture code to store in the DB

Its returning the string ok but I am unable to remove the quoted strings to save the code in the DB
 

 Dim jResults As Object = JObject.Parse(Json)
        Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Json)
        Dim firstItem = jsonResulttodict.Item("error")
        Dim seconditem = jsonResulttodict.Item("success")
        Dim thirditem = jsonResulttodict.Item("codes")

example string:

'{"error":"","success":"1 code generated successfully","codes":["QTESTA2HLT"]}


I am getting the code as [{  "QTESTA2HLT"  }]

Al I want is to read as QTESTA2HLT

please advise

thanks
0
I am trying to deserialize a string:

[{"balance":239443915909,"pendingFunds":0,"currency":"XRP"},{"balance":37185679,"pendingFunds":0,"currency":"BCH"},{"balance":0,"pendingFunds":0,"currency":"ETC"},{"balance":247,"pendingFunds":0,"currency":"AUD"},{"balance":0,"pendingFunds":0,"currency":"USD"},{"balance":0,"pendingFunds":0,"currency":"BTC"},{"balance":0,"pendingFunds":0,"currency":"LTC"},{"balance":126133303,"pendingFunds":0,"currency":"ETH"},{"balance":0,"pendingFunds":0,"currency":"FCT"},{"balance":0,"pendingFunds":0,"currency":"MAID"},{"balance":0,"pendingFunds":0,"currency":"DAO"}]

But it errors

Error
The code I am using is
private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
           string bal = RetrieveAccountBalance();
            AccountDetail Details = JsonConvert.DeserializeObject<AccountDetail>(bal);
        }
       #region Account Methods

 public class AccountList
        {
            public List<AccountDetail> data { get; set; }
        }

        public class AccountDetail
        {
            public string balance { get; set; }
            public string pendingFunds { get; set; }
            public string currency { get; set; }
        }

Open in new window


Could anyone help with this error
0
A 3rd party provider is sending json back to me in this format.

{"specified_lists":["xxxx","yyyy","zzzz","wwww"],"key":"123456789","found":false}

When I execute $json = json_decode($response,true); the last value is not being picked up. How do I read the false statement at the end?

I can get the value of key by using $key = $json->key; but found won't show it's value.
0
Python Gurus--

I am utilizing a 3rd-party API which returns the data I'm looking for in JSON--however, there is a u'foo' in front of everthing. Maybe a unicode thing?  I want to extract the elements to toss into a tabe that has the same element names.

Here's what I am getting:

[{u'comment': u'', u'enableSpeedWarning': False, u'major': 17, u'licensePlate': u'', u'enableMustReprogram': False, u'immobilizeArming': 30, u'engineVehicleIdentificationNumber': u'1XPBDP9X3GD301269', u'isActiveTrackingEnabled': False, u'workTime': u'WorkTimeStandardHoursId', u'isReverseDetectOn': False, u'brakingWarningThreshold': -34, u'gpsOffDelay': 10, u'minAccidentSpeed': 3.0, u'serialNumber': u'G7DF20DBD6F6', u'timeToDownload': u'1.00:00:00', u'maxSecondsBetweenLogs': 200.0, u'isSpeedIndicator': False, u'id': u'b18', u'customParameters': [], u'hardwareId': 551278326, u'name': u'1579', u'activeFrom': datetime.datetime(2017, 7, 31, 18, 13, 27, 296000, tzinfo=<UTC>), u'corneringWarningThreshold': 26, u'deviceType': u'GO7', u'disableBuzzer': False, u'accelerometerThresholdWarningFactor': 0, u'speedingOff': 90.0, u'minor': 59, u'productId': 109, u'odometerOffset': 0, u'isDriverSeatbeltWarningOn': False, u'deviceFlags': {u'isGarminAllowed': True, u'isOdometerAllowed': True, u'isTripDetailAllowed': True, u'isIridiumAllowed': True, u'isEngineAllowed': True, u'isVINAllowed': True, u'activeFeatures': [], u'ratePlans': [], u'isActiveTrackingAllowed': True, u'isUIAllowed': True, u'isHOSAllowed': …
0
Free Tool: ZipGrep
LVL 10
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

I'm looking to consume an external Rest API Json data source into a SharePoint Online list column. I have the enterprise version with BCS.  Anyone had luck with this?
0
I am trying to do something similar to the app specs below.  I'm looking for a sample.  I thought I would use Asp.net Core MVC,  Ajax and SQL server.  I'm looking for a sample that can show me each step.

It's pretty simple.
1. My app has a form with 4 fields. (Vin, Make, Model, Year)
2. I input Vin in field 1 (Vin)
3. I GET from a third party Rest API JSON by passing the Vin to a URI string. The string will pass Vin I input and an API key
4. The API returns (Make, Model, Year)
5. I want to fill the additional form fields with (Make, Model, Year)
6. Finally, I want to save all fields (Vin, Make, Model, Year), to my Database.

I have been searching for an example similar.  I did find the Weather app example, but it's not complete.  It's just part of it.
Weather example: https://www.codeproject.com/Articles/1180283/How-to-Implement-OpenWeatherMap-API-in-ASP-NET-MVC
0
Hello,

I am trying to parse JSON file through JAVA program that has nested objects and arrays.

I am attaching the sample JSON file and the expected results.

I am also attaching the JAVA class program that I am currently using but it only prints the first object and the values related to it. I want the JAVA code to loop through each object and find the nested objects within it and print it as well.

import java.io.FileReader;
import java.util.Iterator;
import java.util.Set;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
 
/**
 * @author Crunchify.com
 */
 
public class CrunchifyJSONReadFromFile {
 
    @SuppressWarnings({ "rawtypes" })
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
 
        try {
 
            Object obj = parser.parse(new FileReader(
                    "/Users/username/Documents/Work_Items.json"));
            
        
            JSONObject jsonObject = (JSONObject) obj;
 
            Set keys = jsonObject.keySet();
            Iterator a = keys.iterator();
            while(a.hasNext()) {
            	String key = (String)a.next();
                // loop to get the dynamic key
                String value = (String)jsonObject.get(key).toString();
                System.out.println("key : "+key);
                System.out.println(" value :"+value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Open in new window

Can someone please assist?

Thank you
sample.txt
Book2.xlsx
0
Hi,

My button don't work but alert work after success, what should I do ?


<!DOCTYPE html>
<html lang="fr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/gif" href="img/drapeauBruxelles.gif" />
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <title>Projet Map</title>
    <style>
       #map {
        height: 600px;
        width: 90%;
       }
    </style>
  </head>
  <body>
    <div class="container-fluid bg-2 text-center">
      <h1 class="margin">Des Marqueurs Google Maps</h1>
    </div>
    <div id="map"></div>
    <nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="https://developers.google.com/maps/documentation/javascript/adding-a-google-map?hl=fr">My Google Maps</a>
        </div>
        <div class="collapse navbar-collapse" id="myNavbar">
          <ul class="nav navbar-nav navbar-right">

            <li><button type="button" id="btn1">Fontaine d'eau</button></li>
            <li><button type="button" onclick="actionImmediate();">Fontaine d'eau</button></li>
   

Open in new window

0
Hello,

I am trying to parse a JSON format data that is stored in oracle CLOB data column. There are multiple/nested objects in the JSON data so I need a query to automatically get all the object/parent name and the value related. Please see attached is the sample example of the JSON data  and the expected output.

I tried the below query but it only gives the value and not the object/Key name.

SELECT jt.*
FROM   JSON_DOCUMENT_lob a,
       JSON_TABLE(json_msg, '$."Additional Statement No".*'
         COLUMNS ( 
           "Attribute/Parent" varchar2(32000) PATH '$.parent()',
           "Value" varchar2(32000) PATH '$'
       )) "JT";

Open in new window


Please assist.

Thank you
SampleData.txt
Book2.xlsx
0
PS: This issue is only happening when i see result in swagger ui , i visual studio it looks fine.

I am trying to replace the string which i have

\\/Date(1430370000000+0530)\\/
to

\/Date(1430370000000+0530)\/
Code:

 string str = "\\/Date(1430370000000+0530)\\/";
 str = str.Replace(@"\","\\");          
 Console.WriteLine(str);
See here the code running environment, click here

Output i am getting above is this :

\/Date(1430370000000+0530)\/
But while we pass the value in JSON property.

The value automatically converts to below value

/Date(1430370000000+0530)\\/
But I am expecting the same value which I got earlier

\/Date(1430370000000+0530)\/
0

JSON

547

Solutions

573

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