JSON

738

Solutions

733

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

I start with the following codes with mvc/json/c#
and I just want to know how to get the following items
Or there is easier way to get everything inside of json file. that will be great.


rating
open now
weekday text
viewport
photos height
photos html_attributions


https://developers.google.com/places/web-service/search

WebClient wc = new WebClient();
string jsonStr = wc.DownloadString("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.753,-122.443&radius=10000&type=rv_park&key=AIzaSyCietasdfasdfasdfasdfxzD65Uc19X6DgrJFumdi-nCZYSHjg");
GooglePlacesResponse gpr = (GooglePlacesResponse)JsonConvert.DeserializeObject<GooglePlacesResponse>(jsonStr);
Response.Write(gpr.status + "<br><br>");

Open in new window

0
Cloud Class® Course: Microsoft Azure 2017
LVL 12
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

I am new to PHP OOP.

I am writing a web app for our company to create Mock API's - which will allow developers to write their code against a Mock API which will return a JSON object.

In its most simple form, it would look like this:

Html Form

Endpoint Name: _________
Method: [GET] [POST] etc
Response Body:_____________________________________________  ( Json Obj )

Open in new window


I understand the basics of creating a class. And defining the information we need. Such as...

class Api {

     private $id;
     private $apiName;
     private $apiMethod;
     private $responseBody;

     public function CreateApi(){
         // Create and insert API into Database
     }

}

Open in new window


My questions are:

1. If I was to have a Database class, how would I use it withing this API class? For instance, as you see below, I am setting a variable $pdo that I can use. How do I pass this into my Login so I can query the user table?

$host =  'localhost';
  $user = 'root';
  $password = '123456';
  $dbname = 'pdoposts';
  // Set DSN
  $dsn = 'mysql:host='. $host .';dbname='. $dbname;
  // Create a PDO instance
  $pdo = new PDO($dsn, $user, $password);

Open in new window


2. How would I structure my includes in this? For instance, do I require_once db_class on every page? For instance, do I do something like this:

include_once("db.class.php");
include_once("login.class.php");

etc , on every page????

Open in new window


3. Lastly, We have this project hosted on Godaddy. I am having problems seeing errors. All I get is a 500 page. I tried the following:

ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);

Open in new window


that is not working. I still only get the 500 error page, not telling me anything.

Can anyone help me out? Thank you.
3
Dear Experts,
when I use it like below code php for json, it gives me the error although it works.

$dosyaadi="something";
$myObj->dosya = $dosyaadi;
$myObj->url = "www.mydomain.com/$dosyaadi";

$myJSON = json_encode($myObj);

echo $myJSON;

Open in new window


it writes the Json but it gives the below code? Json works. But it gives error code

Error:
Warning: Creating default object from empty value in /home/nkolaydeponet/public_html/film-yeni-json-yedek2.php on line 118
0
I was looking at this code and don't understand why there are so many "JSON.stringify" uses? I'm assuming it is completely wrong. Won't it change the string every time you use it? Also wouldn't it just be OK to only use this line var json = JSON.stringify(xhttp.responseText); since that stringifies everything and remove all the others?
                var idAtSource = Math.random().toString(36).slice(-5);
                var now = new Date().toJSON().slice(0, 10) + " " + new Date(new Date()).toString().split(' ')[4];
                var referralUrl = encodeURIComponent(_satellite.getVar("Full URL"));
                var jsonAction = JSON.stringify(action);
                var postBody = JSON.stringify(
                    {
                        "idAtSource": idAtSource,
                        "campaignType": "action",
                        "rawValueEncoded": jsonAction,
                        "referringUrl": referralUrl
                    }
                );

                var xhttp = new XMLHttpRequest();
                xhttp.open("POST", postUrl, true);
                xhttp.setRequestHeader("Content-type", "application/json");

                xhttp.onreadystatechange = function () {//Call a function when the state changes.
                    //readyState 4 is completed, status 200 or 201 is fulfilled
                    if (xhttp.readyState == 4 && (xhttp.status == 200 || xhttp.status == 201)) {
                        var json = 

Open in new window

0
Working with some cascading selects which are json populated.  I need set the select value with a previous selection which has been saved in a mysql table.  

I have found that I can load the select if I pause the page with a alert().


----------------------------------------------------
form1.finish.value="<?php echo $row_Quote['Hdw_finish']; ?>";                              // load the finish select

if ("<?php echo $row_Quote['Hdw_finish']; ?>" != "Select Hardware Finish") {          // trigger finish change  
      $("#finish").trigger("change");
}

alert("pause1");
 
form1.Pull_type.value="<?php echo $row_Quote['Pull_type']; ?>";                               // load Pull_type
if ((form1.Pull_type.value != "Select Pull Type")&&(form1.Pull_type.value != "")) {      // trigger Pull_type change
    $("#Pull_type").trigger("change");
}

alert(pause2);

form1.handle.value="<?php echo $row_Quote['Pull_name']; ?>";                               //  load selected handle

---------------------------------------------

This does set the selects correctly, but without the alerts() it doesn't.  There has to be a right way to do this and this isn't it.
0
Hi guys,
I am using asp.net mvc 5 and I have one controller that initiate the first page.
something like this:
http://localhost:60219/documentviewer/index.

Now I am calling a service from serviceConfig.json. which look like this:
{
   "_comment_": "This file is used if an external application needs to change the values the client application will use to communicate with the service.",

   "licenseDirectory": null,

   "serviceHost": "http://localhost:60219/",
   "servicePath": "",
   "serviceApiPath": "api/",

   "app3": "",
   "app4": "",

   "GoogleDriveLoad_ClientID": "",
   "GoogleDriveLoad_APIKey": ""
}

Open in new window


when I call this json file I am trying to get this link
http://localhost:60219/api/test, but instead I am getting - http://localhost:60219/documentviewer/index/api/test

my question is: how can I get read of the controller and view from the first page and return just -http://localhost:60219/api/test


Thank you.
0
I have created an Xpage custom Rest Service to retrieve a JSON value field from a document.

I take that field value and add other JSON values to a string variable (strJSON).

How can I validate the string variable contains valid JSON?

I receive an error ("'JSON' not found") with the following regardless if the string contains valid JSON:
JSON.parse(strJSON)
0
Next code create triangles on canvas, if you are not clicking over an existing triangle. And you may save all elements to JSON with clicking on "save" button.Then preview the JSON variable in console.

My problem is that after resizing of an object, height and width are not updated in Json when clicked on save again.

What action must I perform to have also new height and width of the object?

 //HTML
    <input type="button"class="Btn1" id="saveJsonID" value="Save"/></br><br>
    <canvas  id="c5" width="1060" height="550"   style="border: 1px solid black"></canvas>

    //JS
     var canvas = new fabric.Canvas('c5');
      
function some1(x1,y2){
           var c = new fabric.Triangle({
              left: posX2,
              top: posY2,
              width:15, 
              height:25,
              strokeWidth:3,
              fill:'#666',
              stroke: '#666'   
            });
         canvas.add(c);
        }
        
 var  posX2 , posY2 ;
  canvas.on('mouse:down', function(e) {
        var circle1=[];
           var pointer = canvas.getPointer(e.e);
                posX2 = pointer.x;
                 posY2 = pointer.y;
              if (e.target){}else{some1(posY2,posY2);}
          });

function saveJsonF(){ 
        var jsonToPHP= JSON.stringify(canvas.toObject());
        console.log(jsonToPHP);
        }
  document.getElementById("saveJsonID").onclick = saveJsonF;

Open in new window

0
I am setting up an integration with a third party.   They already have an existing POST to a former affiliate, so I ask them to just put my URL in there and hit our site.  I figured I would just deserialize the JSON and see what comes in, then code to that.  

So I created a   index.cfm file (Coldfusion 11)  on    www.mysite.com/api/order/    

The index.cfm file does nothing but email me a CFDUMP of the URL and FORM variables.
I gave the URL to the company and they hit it.   I receive the email and both CFDUMPs are empty structures.   No URL variables, no FORM variables.

They say they are doing a POST call to the site.   And are using this path:     www.mysite.com/api/order/   

They have hit it multiple times, they get a 200 OK response.   But each time, my mailed dump show empty values even though they are sending JSON over.

What am I missing?    What do I have to do differently to see the data they are sending?

Thanks!
0
I need to make a vbscript utility code to enumerate subobjects in a JSON.
I load the JSON as follows:
        
Set so = CreateObject("MSScriptControl.ScriptControl.1")
so.Language = "JScript"
so.AddCode( "var json = " + json_text + ";" )

Open in new window

And then accessing the objects as follows:
set subobject_ref = so.Eval("json['subobject_name']")

Open in new window

What if 'subobject_name' is unknown? How can I enumerate all child properties of the root object or a given subobject?

set json_ref = so.Eval("json")

Open in new window

actually creates an object with subobjects/properties, but "for each" can't work with it.
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 have this code to convert the input file to JSON format as per the attached outputFile.txt.  Instead of manually creating the JSON file I'd like to serialise an object using the JSON library.  How do I do this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ChicagoBulls
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ConvertHeightToCentimetres ch = new ConvertHeightToCentimetres();
                
                //string line2 = "";
                var rows = new List<Players>();
                using (StreamWriter sw = new StreamWriter(@"D:\Documents\Tests\ExecView\Test2\ChicagoBulls\chicago-bulls.json"))
                {

                    foreach (var line in File.ReadAllLines(@"D:\Documents\Tests\ExecView\Test2\ChicagoBulls\chicago-bulls.csv"))
                    {
                        //line2 = line.Replace(@"""", "");
                        var data = line.Replace(@"""", "").Split(',');
                        int number;
                        
                        if (int.TryParse(data[0], out number))
                        {
                            rows.Add(new Players
                            {
                                ID = int.Parse(data[0]),
                                Position = data[1],
                                Number = int.Parse(data[2]),
   

Open in new window

0
0
In our ASP.Net MVC web application (C# code), when we are sending JSON request to client server then we received "access-control-allow-origin" error.

Exact Error message received is "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.dial2insure.com' is therefore not allowed access."

if we add "Disable CORS 1.0.3" extension in Google Chrome then we received response json from client server.

4-5 days before I received proper response without this error (no change in code in between).

please suggest what corrections/code we add in our coding sequence and where so that we can get json response from client server without using Google Chrome extension.
0
I need to create an object that I can pass to an API. The object will hold product information ( RMA info ).

Here is how I would like the final object structured ideally:
RMA Number 43454656
    Created Date: today
    Username: John

    Items In RMA
        UPC Code 5345346565564
        qty 3
        // There are 3 items for example with same UPC
            serialNumber: 4534545435435
            serialNumber: 54356546546546,
            serialNumber: 8678678678768

        Next Upc 090909043543534
        qty 1
            serialNumber: 9890895034545

        etc...

Open in new window

Can someone help me build this as a valid Javascript Object / Json Object please?
0
Hi Experts,

   I am trying to loop through json object and filter it into different arrays based on 'group'. Also, trying to assign particular field to a const....I couldn't go beyond

 
 from(Field).pipe(groupBy(fie => fie.group), mergeMap(group => group.pipe(toArray())));

Open in new window


   I would like have this.group1, this.group2, this.gropu3 to have respective Fields after this execution along with this.fieldName1, this.fieldName2 having their respective field values.

  Field object looks like this

 
 Field : [
{ name : fieldname,
  value: FieldValue,
  group: FieldGroup
  }
]

Open in new window

0
I have a stupid question.  I am relatively new to C# and I know I can do what I want to do, but just cannot figure out how.  I have the following code fragment where I am pulling a JSON formatted object from a web API.  I get everything from the connection cleanly and I am able to read it all into the string variable in the code fragment called json and even in the deserialized object jsonEmp.ToString().

The JSON data has the format show below the code fragment.

Here is my question:  All I want to do is walk through the JSON data so that I can pull each individual row out of those two retrieved objects.  I know I should be able to do a 'foreach' statement, but I cannot figure out how to do that.

Basically, here is what I want to do: I want to pull the "Id:", "Name:", and "Description:" from the returned JSON data object and assign them to string variables to display them individually.  But how do I parse the object row to individual string variables?

Can someone point me in the right direction?

Thank you very much in advance,
Jeff


 
                using (var reader = new StreamReader(stream))
                {
                    string json = reader.ReadToEnd();
                    var jsonObj = JsonConvert.DeserializeObject(json) as JObject;
                    var jsonArray = jsonObj["value"] as JArray;

                    foreach (var jsonEmp in jsonArray)
                    {
                        var obj = 

Open in new window

0
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
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
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
Cloud Class® Course: CompTIA Healthcare IT Tech
LVL 12
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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

JSON

738

Solutions

733

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