JSONSponsored by Jamf Now

715

Solutions

718

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

In the example code below, I'm attempting to set variable varB to the same value as varA.

$strJSONdata = @"
    {
        "variables": {
            "varA": "myVariable",
            "varB": "[variables('varA')]"
        }
    }
"@

$objJSON = $strJSONdata | ConvertFrom-Json
write-host $objJSON.variables.varA
write-host $objJSON.variables.varB

Open in new window


But when i execute this script, the ouput is:
myVariable
[variables('varA')]

Open in new window


To be clear, I expected the output to be:
myVariable
myVariable

Open in new window


What is the correct syntax to refer to the value of another variable within the same JSON file.

By the way, I based my example on this web page:
https://docs.microsoft.com/en-us/azure/architecture/building-blocks/extending-templates/objects-as-parameters
0
Upgrade your Question Security!
LVL 12
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

I'm writing a C# .Net function that reads a Json message sent as part of a HttpRequest. The HttpRequestMessage includes the Json message as in an encoded format and as a parameter as follows (for example):
url%3Dhttp%3A%2F%2Fwww.somewebsite.com%2Fsomepage%26page_name%3Dsomepagename%26%26data.json%3D%7B%22time_submitted%22%3A%5B%2209%3A51+PM+UTC%22%5D%2C%22emailaddress%22%3A%5B%22someoneemail%40yahoo.com%22%5D%2C%22device%22%3A%5B%22desktop%22%5D%2C%22page_uuid%22%3A%5B%22ac272d63-abcd-4d38-8ee6-5d36875ea098%22%5D%2C%22fc_referrer%22%3A%5B%22%28not+set%29%22%5D%7D

The problem I have is how to read and decode the Json data in my C# function (the function is running in Azure).

My code starts like this:

using System.Net;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)

{

    string jsonContent = await req.Content.ReadAsStringAsync(); //This works fine and reads the encoded Json message
   
     JObject o = JObject.Parse(jsonContent); // This comes back with error: Newtonsoft.Json: Unexpected character encountered while parsing value: p. Path '', line 0, position 0.


If I test using a decoded httpsrequestmessage, everything works fine. However, with the encoded Json value, I can't read the data. The encoded Json data is sent from another system so I have no control to …
0
I am integrating into a webservice, it returns json, here are 2 types of results from it
{"numFound":1,"QTime":77,"attributions":"http://www.gisgraphy.com/attributions.html","result":[{"id":100004730,"lng":36.710459425750635,"lat":-1.336961662155654,"streetName":"Marula Lane","city":"Bulbul","state":"Kajiado","countryCode":"KE","geocodingLevel":"STREET","distance":300.4280656229352,"adm1Name":"Kajiado","formatedFull":"Marula Lane, Bulbul, Kajiado, Kenya","formatedPostal":"Marula Lane, Bulbul","speedMode":"OSM","maxSpeed":"30 mph","azimuthStart":267,"azimuthEnd":251,"length":1161.411457366,"sourceId":33136013}]}



{"numFound":1,"QTime":2537,"attributions":"http://www.gisgraphy.com/attributions.html","result":[{"id":22523950,"lng":36.81669998168945,"lat":-1.2833000421524048,"zipCode":"09831","city":"APO AE","countryCode":"US","geocodingLevel":"CITY","distance":13413.984061400277,"formatedFull":"APO AE,  (09831), United States","formatedPostal":"APO AE, 09831"}]}

Open in new window


I've used the visual studio paste special as JSON class on the first result as that seems to have more info
I'm using the 2nd result as the  test scenario

I then use this code
Result json1 = JsonConvert.DeserializeObject<Result>(jResult);

Open in new window


But all the objects are empty or null

What am I doing wrong?
0
Is there a better way to convert a json of format
 
object {
field [
{
 @name : fieldName
  @value: fieldvalue
},
......
 (around 100 of this)
]
}

Open in new window

to
object{
field {
fieldname1 : value1
fieldname2:  value2
}
}

Open in new window


so far I could think of only creating a cutome .ts class with all different fieldNames (like fieldName1, fieldName2..etc) and assigning respective values to those by iterating through field array. Feels like very original/basic solution.
0
How to Add MIME type like .json  type in iis by installer.
0
Hi, I am writing ASP.NET Web API to run on Windows/Azure.
What .Net Framework would you prefer 4.* or Core?

Thanks.
0
In terms of JSON - when is one's website both a website and an organization?
0
Hi,

Need examples of best basic JSON-LD schema information for website homepage.  What looks good?  Just dipping my toe into the JSON water.  Getting penalized by Google a bit now.  Want just to cover the basics.  Will customize once I know more.  Just enough to pass the bar, as it were.

Need a few homepage examples - site I could see, please.  Sites with a few pages / sections to them.

For what its worth, in looking around and getting more confused, here's what I've seen.  These are obviously huge sites.  Looked at them for proper structure.  Hoping to find a short set of must haves from you friends and on a site that codes them well to get me out of the gate.

// WashingtonPost Schema ------------------------------------
{
  "@context":"http://schema.org",

  "mainEntityOfPage":{
    "@type":"WebPage",
    "@id":"https://www.washingtonpost.com"
  },
  "headline":"Washington Post: Breaking News, World, US, DC News &amp; Analysis",
  
    "description":"Breaking news and analysis on politics, business, world national news, entertainment more. In-depth DC, Virginia, Maryland news coverage including traffic, weather, crime, education, restaurant reviews and more.",

"image":["https://www.washingtonpost.com/pbox.php?url=https://www.washingtonpost.com/pb/resources/img/twp-social-share.png&amp;w=1484&amp;op=resize&amp;opt=1&amp;filter=antialias&amp;t=20170517"],

  "isAccessibleForFree":"True",
  "hasPart":{
    "@type":"WebPageElement",
    

Open in new window

0
JSON Formatting Tool

What is the best tool (that's quick & easy) to take JSON in a "paragraph/horizontal" format,
and format it into the "common way" vertically so it's easier to read?

Even better, if you can do the same thing, but convert to YAML (vertically).

It can be a standalone tool if need be...or some kind of plugin. FYI...I typically use Visual Studio 'Code' for my
text editor in general, so if that helps with any ideas. However, I'm open to use other suggestions, at least for this purpose.

When I decode AWS encode errors messages, it comes out all smashed together in a horizontal format, almost as
cryptic as the encoded message itself and it's hard to read.
0
I have response object which is a JSON array:

Field:[ 
{
   name: "fieldName1"
   value: "fieldValue1" 
},
{
   name: "fieldName2"
   value: "fieldValue2" 
},
......
]

Open in new window


I have like hundreds of fields like that. I have a need to pass this object to different Angular component and extract out certain fields. Is there a better was to do this in Angular HTML template without having loop through all fields every time I need a particular field in a component? Custom filter pipe will also loop through entire array.
0
Cloud Class® Course: Microsoft Windows 7 Basic
LVL 12
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

I am new to Angular and using Angular 6 CLI. Problem I have is, I have a JSON object that I am getting data from http.get and then trying to parse out different JSON blocks in an object. Then I am passing these objects to respective components. I can see that in the subscribe block the data is populated correctly but outside subscribe block, those objects are 'undefined'.

So from any .ts file, the objects outside subscribe block is undefined. However, I could access data from template files that is from .html files.

for example,  below is where I am calling service from "Component A" so component A has "myappRoot", "myapp", "myproblem"..etc all objects of custom type defined. The custom type is basically interface which I am exporting from index.d.ts file. So objects are populated  inside subscribe block is fine. But if I do console.log(this.myproblem) it comes as undefined outside ngOnInit(). If I pass this object to "Component A HTML" file like {{ this.myproblem? | json}} it prints correctly. but if I pass it to some other component B like <app-component B [myproblem] = 'this.myproblme' ></app-component B> and try to do console.log(this.myproblem) in component B.ts file, it comes as undefined.  Is it due to async nature of observables? How do I solve this?

ngOnInit() {
    // lets  make a call and initialized the root object and children
    this.myproblemService.getmyproblem().subscribe(root => {
      this.myappRoot = root;
      this.myapp = root.myapp;
 

Open in new window

0
In Excel I have parsed a json string using ScriptControle (https://stackoverflow.com/questions/6627652/parsing-json-in-excel-vba).

On my local machine this works perfectly.

However, I need to schedule this job on our business remote (cloud) machine. ScriptControl is not available on the remote machine, I assume due to security reasons.

Is there a way to parse a json string using only VBA without using additional libraries?
0
Hi All

I am working on C# Desktop App.  My below code is working fine for retrieving JSON data from api when I am using http url.
 using (var w = new WebClient())
            {
                 var json_data = string.Empty;
                // attempt to download JSON data as a string
                try
                {
                  json_data = w.DownloadString(url);
                }
               Catch(Exception ex)
              {
              }
          }

But when the url started using https, then my above code started giving me following exception.

[System.Net.WebException] = {"The underlying connection was closed: An unexpected error occurred on a send."}

Can anyone Kindly help me sort out this exception.

Thanks in adance.
0
I have a JSON formatted configuration file that I need to load into PHP and work with. Whats the best way to do this?

I was thinking of using file_get_contents and then json_decode to move it into an array.
0
How  to JsonConvert.DeserializeObject :
{"status":"ok","message":"","data":[***Array of json data*********]"}

I have JSON response data above, and i want to get array of data so that i can loop thrue the data...

public class Response<T>
    {
        public string IsSuccess { get; set; }
        public string Message { get; set; }
        public IEnumerable<T> ResponseData { get; set; }

        public Response(string status, string message, IEnumerable<T> data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

Open in new window


And here is code from my function:
if (resp.IsSuccessStatusCode)
                {
                    Console.WriteLine("Request Message Information:- \n\n" + resp.RequestMessage + "\n");
                    Console.WriteLine("Response Message Header \n\n" + resp.Content.Headers + "\n");

                    string responseBody = resp.Content.ReadAsStringAsync().Result;
					var test = JsonConvert.DeserializeObject<Response<string>>(responseBody);
                    
                    Console.WriteLine(responseBody);

                }

Open in new window

0
Hello,
My problem is that the "JsonUtility.FromJson" is not working on Android, only works on the Unity Editor.
This is my code:
IEnumerator LoadStreamingAsset(string fileName)
    {
        string result;
        string filePath = System.IO.Path.Combine(Application.streamingAssetsPath, fileName);

        if (filePath.Contains("://") || filePath.Contains(":///"))
        {
            WWW www = new WWW(filePath);
            yield return www;
            result = www.text;
        }
        else
        {
            result = File.ReadAllText(filePath);
        }
        GameData loadedData = JsonUtility.FromJson<GameData >(result);
        Questions = loadedData.Questions ;
        Debug.Log("Loaded file: " + result);
    }

Open in new window


Any help?
0
I have an array of checkboxes coming from a collection.

See below:

<div class="form-group">
    Select days in a week :
    <td class="even" *ngFor="let item of dayList">
    <input value="{{item.check}}" type="checkbox" checked="item.check" formControlName = "selectedDays">  {{item}}
   </div>

Open in new window


formControlName I am set as selectedDays.

I need to generate JSON object for the selected checkbox values.

Currently, i am getting boolean value in selectedDays. But I am supposed to get an array of checked values in an array inside JSON object.

this.dayList = ['Sun', 'Mon', 'Tue','Wed',"Thu","Fri","Sat"];

JSON Object looks like below, please note the value of selectedDays, it is supposed to be "Sun, Mon" based on selection, but it is showing as true.


 
Object
    date
    :
    "2"
    day
    :
    "Mon"
    hour
    :
    "3"
    minute
    :
    "3"
    schedulerjobtype
    :
    "Daily"
    selectedDays
    :
    true
    useCase
    :
    "UC 2"
    zone
    :
    "Zone 3"

Open in new window


How can I implement this?
0
Working with Client-Side CFCharts and passing JSON controls

I'm using the Zoom-In Preview and want to start the graph zoomed-in.

Zoom-In feature of CfChart, with an initial zoom set
The problem is that the setting for initial zoom-in does not seem to be a valid parameter in Coldfusion CFChart.
Looking at the ZingChart documentation (which is what CfChart uses)  I see the value I need in the scale-x attribute,   But CFChart says that is not a valid parameter and of course there is zero documentation on it.   Does anyone know how to include the scale-x attribute?


<cfset variables.xAxis = {"label"={"text"="Drag the handles to zoom in to the chart","color"="red"},"zooming"="true"}>
<cfset variables.yAxis = {"label"={"text"="Drag the handles to zoom in to the chart","color"="red"},"zooming"="true"}>

<cfset variables.zoom = {"alpha"="0.3","zooming"="true","zoomTo"="[10,30]","adjust-layout"="true","border-color"="black","border-width"=4,"background-color"="gray","label"={"border-color"="red","border-width"=2,"font-size"=10}}>

<cfset variables.preview = {"alpha"="0.3","visible"="true","live"="true","preserve-zoom"="true","border-width"="2","vertical-align"="top","adjust-layout"="true"}>

<cfset variables.plotArea = {"margin"="dynamic dynamic 130px dynamic"}>

<cfset variables.scaleX = {"zooming"="true","zoomTo"="[2,5]","adjust-layout"="true"}>   <!==========  I need to set  ZoomTo Value which is part of Scale-X in ZingCharts

  <cfchart alpha=".7"
	   backgroundColor = "##eeeeee"
         

Open in new window

0
I'm trying to get this json data

https://www.cryptocompare.com/api/data/coinlist/

Here's my code

import axios from 'axios';

axios.get("https://www.cryptocompare.com/api/data/coinlist/")
.then((result) => {
  console.log(result);
}).catch((err) => {
  console.log(err);
});

Open in new window


But I'm getting an error



How this error can be fixed to actually get the data?
0
Free Tool: Port Scanner
LVL 12
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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'm trying to iterate through the following object and add the key value pair 'selected: false' to each invoice object in each invoices object in every vendor object array element.  In other words, every invoice object needs 'selected:false'.  ie: {"invoice_id":325,"invoice_amount":434, "selected":false} in every instance.

I've tried fiddling around with a two level nested .forEach method and I can get to the invoice object but I have no idea how to mutate it by adding a property so at the end of the function the new object has the 'selected:false' inserted in each invoice object.  How would you do this?

{
"vendors":[
  {
    "name": "asdf",
    "company": "asdf",
    "invoices" : [
      {"invoice_id":321,"invoice_amount":432},
      {"invoice_id":323,"invoice_amount":431},
      {"invoice_id":324,"invoice_amount":432},
      {"invoice_id":325,"invoice_amount":434}
    ]
  },
  {
    "name": "adfd",
    "company": "aerer",
    "invoices" : [
      {"invoice_id":321,"invoice_amount":556},
      {"invoice_id":323,"invoice_amount":65654},
      {"invoice_id":324,"invoice_amount":343},
      {"invoice_id":325,"invoice_amount":4676}
    ]
  },
  {
    "name": "bvbf",
    "company": "acv",
    "invoices" : [
      {"invoice_id":321,"invoice_amount":474},
      {"invoice_id":323,"invoice_amount":789},
      {"invoice_id":324,"invoice_amount":4898},
      {"invoice_id":325,"invoice_amount":855}
    ]
  },
  {
    "name": "hgh",
    "company": "yuy",
    "invoices" : [
  

Open in new window

0
i am trying to run

npm install mysql

command in cmd its giving me these error

npm ERR! Unexpected end of JSON input while parsing near '....tgz"},"engines":{"no'

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-05-30T06_49_09_337Z-debug.log
0
Using Cold Fusion - How to parse this JSON feed that has structure - array - structures.

I've attached a jpg of the cfdump

I just don't work with structures and arrays much anymore
Structure.jpg
0
Basically I am trying to pre-populate a select based upon a value.

I have this edit modal that shows up when the user clicks EDIT row in a data table:



I am populating everything except the USER TYPE drop down, as you can see.

The usertype id of the row being edited , is available to me in this global variable:

currentRow.userType

Open in new window


I am obtaining an array of all usertypes from an ajax call and put in variable:

var modelLookup;

Open in new window


Sample JSON Response:
[
 {
    "id": 0,
    "name": "admin",
    "active": true
  },

 {
    "id": 1,
    "name": "user",
    "active": true
  }
]

Open in new window


and my select looks like this:

<select id="userType" class="form-control">
                            <option selected>Select User Type</option>
                            <option value="">user type here</option> 
                        </select>

Open in new window


So basically I need all usertypes in the dropdown, with the one with the id of currentRow.userType selected.

Can anyone help me out please?
0
If anyone could help me understand why the convert() method code is producing this output in patientout.json:

[
    {
        "patientid": "1235",
        "sex": "female",
        "name": "Jane Smith",
        "state": "OH",
        "age": 47
    },
    {
        "patientid": "1235",
        "sex": "female",
        "name": "Jane Smith",
        "state": "OH",
        "age": 47
    }
]

Open in new window



Instead of this output:
[
       {
              "patientid": 1234,
              "sex": "male",
              "state": "MI",
              "name": "John Smith",
              "age": 55
       },
       {
              "patientid": 1235,
              "sex": "female",
              "state": "OH",
              "name": "Jane Smith",
              "age": 45
       }
]

Open in new window


I would appreciate it.




The patientin.xml input file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<patients>
  <patient>
       <id>1234</id>
       <gender>m</gender>
       <name>John Smith</name>
       <state>Michigan</state>
       <dob>03/04/1962</dob>
  </patient>
  <patient>
       <id>1235</id>
       <gender>f</gender>
       <name>Jane Smith</name>
       <state>Ohio</state>
       <dob>08/24/1971</dob>
  </patient>
</patients>

Open in new window



The convert() method can be found in file XMLtoJSONConverter.java
0
This is a multipart form, so I am using FormData.
<form id="PriceForm" name="PriceForm" method="post" enctype="multipart/form-data" accept-charset="UTF-8">

Open in new window

I am using this same code in 2 other modules, and it is working fine. It appears it is not even reaching the PHP file, and I have run out of ideas to troubleshoot.
In the code below, I am pressing the "Save" button, which is recognized, and I have verified that it is sending correctly populated variables to DataSave.
Validation comes back positive (also verified)

What I have done to troubleshoot

1. Verified, line by line, that the code sequence is identical to what is working elsewhere.
2. Placed error information in the PHP file ($Error[] = "Testing";)
3. Finally, created a simple test file (shown at bottom) to return a result. There was no change, so it does not seem to be in the PHP file.

The button listener (I am selecting the "Save" button)
$(document).ready(function()
{
   $(document).on('click', '.SubmitButton', function(e)
   {
      e.preventDefault();
      var ButtonID = $(this).attr('id');
      var Form = $('#PriceForm');
      var Validate = false;
      if(ButtonID == "Reset")
      {
         if(confirm("Did you mean to clear the form?") == true)
         {
            ClearURI();
            window.location="pricing.php";
         }
      }
      else if(ButtonID == "Save")
      {
         var Data = new FormData(Form[0]);
         Data.append( 'Sec', 

Open in new window

0

JSONSponsored by Jamf Now

715

Solutions

718

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