JSON

477

Solutions

6

Articles & Videos

517

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

So, I am really trying to get my head around JSON and I have tried this which works but I wanted to know if there is a better way to do it or if this okay. I am actually playing around with developing a hybrid mobile app which uses a php and mysql backend. I have to use ajax to retrieve data and I want to also use JSON.

This is the jQuery/Ajax. The double dollar signs are not a typo, that is the correct syntax for the application but it is identical to jQuery as far as I know.

$$( "#submit" ).click(function(e){
		$$.ajax({
			url:"content.php",
			type:"POST",
			dataType:"json",
			success: function(data) {
				var len = data.length;
				for(var i = 0; i<len; i++) {;
					var user_name = data[i].user_name;
					$$( "#phpcontent" ).append(`
					<li class="item-content">
						<div class="item-inner">
						<div class="item-title">${user_name}</div>
						</div>
					</li>
					`);
				}
			}
		});
	});

Open in new window


This is the php for content.php

$stmt = $link->prepare("SELECT `user_name` FROM `users` ORDER BY `user_name` DESC");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
	while($row = $result->fetch_assoc()) {
		$user_name = sanitize($row['user_name']);
		
		$return_array[] = array(
		
			"user_name" => $user_name
		
		);
	}
}
$stmt->close();
echo json_encode($return_array);

Open in new window


What I have noticed in all the examples I have looked at is that the database results have to be put into an array in order to use json_encode. Am I correct in saying that or is it just a coincidence that every example I looked at did that?
0
Free Tool: Site Down Detector
LVL 8
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 have a simple html page that uses bootstrap grid.

Each page of the grid I've labelled as a section.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  </head>
  <body>

  <div class="container">

  	<div class="row">
  		<div class="col-md-4">Section 1</div>
  		<div class="col-md-4">Section 2</div>
  		<div class="col-md-4">Section 3</div>
  	</div>

  	<div class="row">
  		<div class="col-md-6">Section 4</div>
  		<div class="col-md-6">Section 5</div>
  	</div>

  </div>
 

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </body>
</html>

Open in new window


Example data:

{
  "section": "section1",
  "position": "5"
}

Open in new window


What I want to do is to load the different grid parts by reading json data.

So basically, the page loads, reads the json data which contains the positions of the sections and then populates the website.
0
I am using a webclient to send data via JSON to tell the server what I want to have them return to me. However, The API requires I use a GET. But I don't know how to define a GET in the UploadData or even DownloadString methods. How can I issue a GET at the same time I am also sending JSON?

If I pass all the parameters as query string parameters it also fails, so I have to issue the call using JSON data in the body.

thanks!
0
I am using REST API with SharePoint 2013 and I want to know if the following url endpoint is legal or if there is a better way?
 //http://myspsite.com/nrm/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq '402-CSI-001'     //<---  Works when I paste it in the browser
 var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=DIR,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;  //<---  Not valid when I run it in my code

Open in new window


Error I get in my js file
rest api error
js file
function loadSPItems() {
var projNum = '402-CSI-001';
var endPointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbyTitle('My_Project_Modules')/items?$select=VISN,Station,Title,Building_x0020_Number&$filter=Project_x0020_Number eq "+projNum;//,ProjectNumber,ApprovalStatus,ProjectExecutionStatus”;
var headers = { 
	"accept": "application/json;odata=verbose" 
}
 
jQuery.ajax({ 
	url: endPointUrl, 
	type: "GET", 
	headers: headers, 
success: function (data) {
	console.dir(data);
}, 
	error: function (err) { 
	alert("Error Occured:" + JSON.stringify(err)); 
}
 
});
 
}

loadSPItems();

Open in new window




Thoughts?
0
Hi,

I have been playing with the following
https://developers.google.com/chart/interactive/docs/gallery/timeline
from within a PHP app.

So far so good: I am able to show data coming from a PHP function (selecting data from a MySQL DB) and also able to export in JSON format to allow the chart to showup, but ...

...I find no way to change tooltip data, or simply change duration format (it seems I cannot decide a fixed format like h m s instead of the default by day).

The data I am using to feed the chart include hours, minutes and seconds

Anyone who has experience on this can confirm if:
 1 - It is possible to change duration format and how
 2 - It is possible to change tooltip content/format and how

Thanks in advance
0
i have  JSON from a firebase database and I want to put the data in an HTML table, preferably with Javascript

Tried a few examples on the web but cant get anything to work, Im not sure how to reference each piece of JSON
...trying things like snap.val().site and snap.val()[0].site and get error message undefined

can someone please point me in the right direction

JSON...
{
"-KkKsqJ9VyBILEg-DOPX": {
"direction": "SSE",
"email": "anita@gmail.com",
"site": "Bridges",
"speed": "5-10",
"status": "Flyable",
"statusDescription": "Epic"
},
"-KkKvkBn_kAR0YB1hIX_": {
"direction": "E",
"email": "joe@gmail.com",
"site": "Moirs",
"speed": "10-15",
"status": "Flyable",
"statusDescription": "Its OK"
}
}

Open in new window


Table
<table id="displayData">
  <tr>
    <td>Direction</td>
    <td><email/td>
    <td>Site</td>
    <td>Speed</td>
    <td>Status</td>
    <td>StatusDescription</td>
  </tr>
</table>

Open in new window


Div...
<div id = "display"></div>

Open in new window



JS...
//reference table and div
const firedata = document.getElementById('displayData');
const display = document.getElementById('display');

//create reference
const dbRefObject = firebase.database().ref().child('posts' );

//sync changes
dbRefObject.on('value', snap => {
  
//Display data in an HTML Table
//????????????

//display JSON in a div - works ok, returns the JSON above
  display.innerText = JSON.stringify(snap.val(), null, 3);

//display in console - works ok
  console.log(snap.val()); 
});

Open in new window

0
Hello there,

I want to create a csv file from a JSON string which I get from the backend. But I need to select which of the key value need to go into the csv file. For e.g. below is my JSON which I get from the server. I want to only export 5 key values i.e.
"speed":"10","max":"20","upper":"70","platform":"90","platformyposition":"95"

{"df":"6767677777777","sup":"11","single_batch":null,"package":"1","multi_batch":null,"shelf":"18","fdoname_en":"HJ","fdoname":"1","newic":"1","gtin":"1","status":null,"route":null,"pcategory":"RRRR","proline":null,"licensetype":null,"gname_en":"asasfff","speed":"10","max":"20","upper":"70","platform":"90","platformyposition":"95"},
{"df":"6767677777777","sup":"11","single_batch":null,"package":"1","multi_batch":null,"shelf":"18","fdoname_en":"HJ","fdoname":"1","newic":"1","gtin":"1","status":null,"route":null,"pcategory":"RRRR","proline":null,"licensetype":null,"gname_en":"asasfff","speed":"10","max":"20","upper":"70","platform":"90","platformyposition":"95"},{"df":"6767677777777","sup":"11","single_batch":null,"package":"1","multi_batch":null,"shelf":"18","fdoname_en":"HJ","fdoname":"1","newic":"1","gtin":"1","status":null,"route":null,"pcategory":"RRRR","proline":null,"licensetype":null,"gname_en":"asasfff","speed":"10","max":"20","upper":"70","platform":"90","platformyposition":"95"}

Open in new window


Please help!!
0
Hello Experts,

I would know  is it possible to implement Auto suggest  through angularjs2. The application has to search  the database and suggest some alternate name while typing in the text.


Thank you
Roy...
0
I am displaying a tree in Angular2 application using angular-tree-component (https://angular2-tree.readme.io).

I need to give user the capability to select any node in the tree and delete it. This should remove the selected node and all it's children (if it's a leaf node, then just the node). When user is done, the pruned tree will be send to the server and saved there.

In the below example, user selects 'Node 1-2' and clicks on Delete. This removes 'Node 1-2, 'Node 1' and 'Node 2' from the view and underlying Javascript object updated. User can then click another button (say, Save) to save the updated object on the Server.
Tree
In order to accomplish this, I wrote the following code which is called on click of Delete button. I store the id of the selected node, and then iterate over the complete tree to find that id. When the id matches, I use the 'delete' keyword to delete 'id' and 'text'. However, 'delete children' does not work.

deleteSelectedNode() { 
    //Get the node which was selected by the user  
    let nodeToDelete: TreeNode = this.myService.getActiveNode();
    //id will be unique, can be used to identify the node
    let idToDelete = nodeToDelete.data.id; 
    this.traverseTree(this.nodes[0], idToDelete);
  }

  traverseTree(obj, idToDelete: string) {

    for (var k in obj) {
      if (typeof obj[k] == "object" && obj[k] !== null) {
        this.traverseTree(obj[k], idToDelete);
      }

      else {
        if (k === 'id') 

Open in new window

0
I have an ASP.Net 4.0 website and I am looking to integrate some JQuery to a web page but I don't know how.
I want to use IP Info API to look get the IP Address and City of the users on my site.  They have provided code snippets here:
http://ipinfo.io/developers#getting-started
How can I integrate this to the client side script of my web page and populate some text boxes with the results on page load?
0
How our DevOps Teams Maximize Uptime
How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Hi. I'm having input xml file, which having double quotes attribute, But i want to change as single quote while doing xml to json process. because json files not allowing double quotes:

My input xml file having:

                  <div class="text-center">
                     <p>
                        <strong> Type:</strong> Unhealthy fat</p>
                  </div>

for Json output I need as:

                  <div class='text-center'>
                     <p>
                        <strong> Type:</strong> Unhealthy fat</p>
                  </div>

I'm using saxon-PE 9.6.0.7 and XSLT version as 3.0. How i can change the double quote to single quote??
0
I have a coldfusion query and I need to search the query by the address with the proximity of 5 miles. The client type their home address and I need to show desired location in the radius of 5 miles
0
How to parse the  JSON Data using Rest web service give me a simple example
0
Dear Experts,
I'm new with sending data in Json format,
Reading posted data in Json format is ok for me. ( Thanks to Ray Paseur )

I use below code on my json.php page. When I visit json.php page, I'm expecting the code runs and the page posts $jsonData to the myurl.php . Normally when I post a data with html form, my page is going to action page, and I'm expecting here the same, I'm waiting to go myurl.php but json.php goes nowhere and it gives no error.

PHP works when a page is called, right? So that I guess, it doesn't post anything, right?

I'm using shared hosting with PHP 5.6

<?php

//API Url
$url = 'myurl.php;

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

Open in new window


//the code is here: http://thisinterestsme.com/sending-json-via-post-php/
0
I am trying to implement a search function in MVC.   In my controller I am returning a JSON Request so I can implement AJAX popup modal for crud.  In my search form in the view I call the view GetMembers which is just returning the JSON data.  I am confused on how to implement the search with the JSON part and keep the "regular list"  while still maintaining the AJAX for CRUD.

 
View:
<div style="width: 90%; margin: 0 auto" class="tablecontainer">
    <p>
        @using (Html.BeginForm("GetMembers", "Members100", true, FormMethod.Get))
        {
            <b>Search By: </b>
            <input type="radio" onclick="ModifyPlaceHolder(this)" id="ID" name="searchBy" value="members_id" placeholder="Member ID" checked><label for="ID"> ID</label>
            <input type="radio" onclick="ModifyPlaceHolder(this)" id="Phone" name="searchBy" value="members_phone"><label for="phone"> Phone</label>         
            <input type="text" id="MyQuery" name="search" placeholder="ID">
            <input type="submit" value="search" />
        }
    </p>

    <table id="myDatatable">
        <thead>
        <tr>
            <th>ID</th>
            <th>renewal date</th>
            <th>Edit</th>


        </tr>
        </thead>
    </table>
</div>

Open in new window


Script
 $(document).ready(function () {
        var oTable = $('#myDatatable').DataTable({
            "paging": false,
            "ajax": {
                "url": "@Url.Action("GetMembers", "Members100")",
                "type": "get",
                "datatype": "json"
            },
            "columns": [
                { "data": "member_id", "autoWidth": true },
                {
                    "data": "member_id",
                    "autoWidth": "50px",
                    "render": function(data) {
                        return '<a class="popup" href="http://localhost/NAHP/Members100/save/' +
                            data +
                            '">Edit</a>';
                    }
                }
            ]
        });

Open in new window




Controller:

Open in new window

0
Dear Experts,
I'd like to learn about PHP and Json, ( posting and receiving data )

How would I post below $myJSON object to myjson.php page ? and how would I print it on the myjson.php page?
Can I post it inside an HTML form? Do I have to use Ajax or something?

What I'm looking for is a good working example. I tried this

<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;
?>

Open in new window


I tried to post it like this but it didn't work I only get "{" as a result when I use below code

<form name="form1" method="post" action="myjson1.php">
  <label for="data"></label>
  <input type="hidden" name="data" id="data" value="<?php echo $myJSON ; ?>">
  <input type="submit" name="send" id="send" value="send">
</form>

Open in new window


$data = $_POST['data'];
echo $data;

Open in new window

0
I have a table called XYZ which has 2 fields one is storing Json Structure and the other is varchar, Those fields look like below.
             HostName, IPAddresses
Row 1 : Machine1, {"ipaddress1":"10.1.112.34", "ipaddress2":"192.168.3.17"}
Row 2 : Machine2, {"ipaddress1":"10.1.113.37", "ipaddress2":"192.168.1.17"}
Row 3 : Machine3, {"ipaddress1":"10.1.112.37", "ipaddress2":"192.168.0.17"}
Row 4 : Machine4, {"ipaddress1":"10.1.112.38", "ipaddress2":"192.168.6.17"}
Row 5 : Machine5, {"ipaddress1":"10.1.112.40", "ipaddress2":"192.168.2.19"}
and I have finished to extract the detail of ip address by using select Hostname , IPAddresses -> '$.ipaddress1' as PrimIP from XYZ

My Question is how can I use "in"  this keyword or something similar for those Json structure as I was using it in a normal SQL structure.
ie. let say I have a range of IP address of the ipaddress1. ('10.1.113.37', '10.1.112.38','10.1.112.40' )
if the IP range is as varchar I can simply using

select hostname , IPaddresses from XYZ where IPAddresses in ('10.1.113.37', '10.1.112.38','10.1.112.40' ).  roll consisted with these ip address will be return.

How can I do the same as above when I am using Json structure at MySQL?
0
Hi Guys,

I'm trying to read json list object through ajax:
Here is my json data return - which basically return 2 rows:
[{"BinLocation":"16A","BuydownPrice":0.0000,"BuydownQuantity":0.0,"CommissionAmount":0.0000,"CommissionMaximum":0.0000,"CommissionMode":0,"CommissionPercentProfit":0.0,"CommissionPercentSale":0.0,"Description":"3  B/G H.D. MYLAR  K","FoodStampable":false,"HQID":139858,"ItemNotDiscountable":false,"LastReceived":"2007-06-07T00:00:00","LastUpdated":"2013-01-18T16:24:06","Notes":null,"QuantityCommitted":0.0,"SerialNumberCount":0,"TareWeightPercent":0.0,"ID":1,"ItemLookupCode":"0839420-EA","DepartmentID":8,"CategoryID":614,"MessageID":0,"Price":0.7900,"PriceA":0.0000,"PriceB":0.0000,"PriceC":0.0000,"SalePrice":0.0000,"SaleStartDate":null,"SaleEndDate":null,"QuantityDiscountID":0,"TaxID":1,"ItemType":0,"Cost":0.2282,"Quantity":27.0,"ReorderPoint":0.0,"RestockLevel":0.0,"TareWeight":0.0,"SupplierID":316,"TagAlongItem":0,"TagAlongQuantity":0.0,"ParentItem":0,"ParentQuantity":6.0,"BarcodeFormat":7,"PriceLowerBound":0.0000,"PriceUpperBound":0.0000,"PictureName":"","LastSold":"2012-12-04T00:00:00","ExtendedDescription":"","SubDescription1":"THE HILLMAN 

Open in new window

0
Hi, trying to pass data from a json file into a Highchart, there is no data in the series.  Am very new to this, can anyone tell me why?
Thank you!


<json>
0
Resolve Critical IT Incidents Fast
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

I need to create map using google map API. I have created a map by the page load.

Also i have filters search by location, search by state, and the school and the search button. So what I need when the user click on the search the appropriate parameter to be send to the query and once the query returns the result place markers on the map. Once marker get clicked display the info from the query
0
Hi folks,

I'm in a bit of a pickle here.  Bottom line, I have a wordpress site and need to update ALL posts on my large site somehow ( something that accomplishes hitting the "update" button within the edit post dashboard (in order to add  a value to a newly added field to the database) . My only guesses are to do it programatically, or wondering if importing a copy of the database might accomplish this (doubtful).  I've scoured the web for this, but the code I've found breaks my site.

To explain why I'm in this situation, I have a custom field that will not register to postmeta in order so that it shows in a json output for a post via the wp Rest Api.

My workaround for exposing these fields to json was to install Advanced Custom Fields plugin and create a copy of the existing custom fields.  If i update a post manually, the new field is visible in a json request (awesome!), but it requires me to update ALL posts to get the json output for that field in every post.

Clear as mud!?

Thanks for any assistance!
0
<div style="margin-right: 10px;margin-top: -15px">
<input type="hidden" name="meal_id[]" value="<?php echo $meal_options_id2?>">
<i id="qty-minus<?=$meal_options_id2 ?>" class="fa fa-minus-circle controls" style="color: #d7d6d0;margin-right:10px"></i>
<input name="qty[]" id="qty<?=$meal_options_id2 ?>" type="number" value="<?=$num_of_meals2?>" min="0" step="1" style="border:1px solid #d7d6d0;background:transparent;width:35px;height:33px;color:#000;font-size:21px;font-weight:700;">		
<i id="qty-plus<?=$meal_options_id2 ?>" class="fa fa-plus-circle controls" style="color: #d7d6d0;margin-left:10px"></i>
</div>

Open in new window


How can I make the plus circle act like a addition of qtys in the input box, and the minus to remove?
And as you can see the id is dynamic? can anyone help?
0
One thing that drives me nuts when I am programming is that during development, I want to stop timeouts. These are espcially annoying when you're stepping through the code and there is a lot of it and by the time you get to where you want to actually see what is going on, it times out. For example. I have web API service that receives JSON data via an HTTP Post. I parse that data and then execute a bunch of stored procedures. I then get the results back from them and build a response and send it back to the caller.

How can I stop the timeouts in IIS, SQL queries, etc? Is there a way at all?

I'm using VS2017 and the code is all C#
0
 [{"ID":416,"Name":"F Trust","ID":1256,"Name2":"MLP ETF","Sling":true},{"ID":416,"Name":"F Trust","ID":1108,"Name2":"Alps Equal Sector Weight ETF","Sling":true},{"ID":416,"Name":"F Trust","ID":998,"Name2":"Cohen & Steers Global Realty Majors ETF","Sling":true}

Open in new window


Result I would like.
 [{"ID":416,"Name":"F Trust","ID":1256,"Name2":"MLP ETF","Sling":true},{"ID":416,"Name":"null","ID":1108,"Name2":"Alps Equal Sector Weight ETF","Sling":true},{"ID":416,"Name":"null","ID":998,"Name2":"Cohen & Steers Global Realty Majors ETF","Sling":true}

Open in new window


for (var i = 0; i < response.length; i++) {
    if (distinctValues.hasOwnProperty(response[i].Name)) {
        //already has it
        response.splice(i, 1);
        i--;
    } else {
        distinctValues[response[i].Name] = false;
    }
}

Open in new window


My Object Name if it repeats for example you see FTrust multiply times then >>> I just want to replace Name with NULL not splice it and deleted it.
0
Hi can any body help in creating the aws cloud formation stack manually or there ia any url that i can use to learn how to create the code for cloud formation stack
0

JSON

477

Solutions

6

Articles & Videos

517

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