JSON

502

Solutions

543

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 have a database query that I want to export or convert to a json file.

The query result is something like this

path                         | name          
parameter.name.menu.myname | mike miller

Open in new window


Finaly I need a json structure like

"parameter": {
        "name": {
              "menu": {
                    "myname": " mike miller"
              }
         }
 }

Open in new window


How this is possible?
I work with mysql 10.1.x and php
0
Learn how to optimize MySQL for your business need
LVL 3
Learn how to optimize MySQL for your business need

With the increasing importance of apps & networks in both business & personal interconnections, perfor. has become one of the key metrics of successful communication. This ebook is a hands-on business-case-driven guide to understanding MySQL query parameter tuning & database perf

UseCase 1 :-  Http Method : Get , expected json is {"id":1, "effecitveDate" :"2017-08-13 08:10"} - working fine

UseCase 2 :- Http Method : Get, expecting a list of objects i.e. ["id":1, "effecitveDate" :"2017-08-13 08:10"} ,"id":2, "effecitveDate" :"2017-08-16 08:10"}

but I am getting  date like ["id":1, "effectiveDate": [
            2017,
            8,
            13,
            8,
            10
        ]},
"id":2, "effectiveDate": [
            2017,
            8,
            16,
            8,
            10]}
]

How to solve this date issue.
Note : I am using java8 LocalDateTime.
0
I have created a controller for a KeyLog (users check in keys or check out keys) from a physical box.  I return a list of log entries to a free fqGrid control via json.  Below is my controller code:
var jsonData = new
            {
                rows = from logs in db.KeyLogs.Where(k => k.KeyId == id).ToList()
                       select new
                       {
                           id = logs.Id,
                           keyId = logs.KeyId,
                           removeDate = logs.KeyRemovedDate.HasValue ? logs.KeyRemovedDate.Value.ToString("MM/dd/yyyy") : "",
                           removeTime = logs.TimeOut.HasValue ? logs.TimeOut.Value.ToString("HH:mm:ss") : "",
                           returnDate = logs.KeyReturnedDate.HasValue ? logs.KeyReturnedDate.Value.ToString("MM/dd/yyyy") : "",
                           returnTime = logs.TimeIn.HasValue ? logs.TimeIn.Value.ToString("HH:mm:ss") : " ",
                           officer = logs.Officer
                       }
            };

Open in new window


The problem is that this code errors on the time vaues if one of them is null.  How can I get around this?  The date vaules are not a problem.
0
Hi Guys,
I send json data from my server to the view in MVC project.

Here is the link I send as a json:
dataCell.textCell = "<a onmouseout='HideFlyOut()' ;="" class='theme_color' onmouseover='ShowFlyOut('" + encryptedRowPass + "') href=\documentviewer.aspx?" + encryptedValue + "'<i class='fa fa-paperclip fa-flip-horizontal fa-2x theme_color'></i></a>"

Open in new window



Now in my UI side I'm getting this data which is one row and parse it to json:

 var sendDataRowsToView = JSON.parse(datarows)

Open in new window


Then I"m trying to place this data into a <td> in my dom:

 tableBody.append('<td> + sendDataRowsToView + </td>')

Open in new window



I'm getting the data and all works fine but it doesn't bind it to the dom:

Like I'm expecting to see for exmaple:
<td><a></a></td> which bind all the link from the server, but for some reason I can't see this data in my dom.

what am I doing wrong?
0
This is my first foray into JSON and I'm trying to develop an autocomplete field with JSON, php and sql.  I've got it working on a single field (employee Name) but would like to add a second field that gets populated by the employee title when the employee name is selected.  

So far, my test page looks like:
<!DOCTYPE html>
<html>
<head>
    <title>Autocomplete Textbox Demo | PHP | jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

    <script type="text/javascript">
        $(function() {
            var availableTags = <?php include('fetchEmpName.php'); ?>;
            $("#empName").autocomplete({
                source: availableTags,
                autoFocus:true
            });
        });
    </script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" />
<input id="empTitle" type="text" size="50" />
</body>
</html>

Open in new window


And the fetchEmpName.php file is like:
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
foreach ($data as $row) {
    $empName[] = $row['empName'];
    $empTitle[] = $row['empTitle'];
}
 $arrData = array($empName,$empTitle);
 echo json_encode( $arrData );
?>

Open in new window


The code is working if I only use the $empName or $empTitle array and encode that ($data = $empTitle or $data=$empName.  

However making an array of both arrays causes the empName box to return two blank lines instead of any names or titles when I type.  I get that, but I don't know what to do about it to access the underlying data and have the names list in text box one and populate the employee title to text box two upon a selection.

As always, thanks in advance for any help offered.
0
I have a page that generates this json output
{"address":"1234 East Main Street","city":"Anywhere"}

Open in new window


I created it using this PHP function on an index.php page
$address="1234 East Main Street";
$city="Anywhere";
echo json_encode(array('address'=>$address,'city'=>$city));

Open in new window


I then have the script shown below attached to the top of the index page that includes this ajax script that should be parsing and returning the values in my console.  I only get error messages

$(function() {

    $.ajax({
        url : 'index.php',
        type : 'POST',
        data : {"address":"address","city":"city"},
        dataType : 'json',
        success : function (result) {
           alert(result['address']); // alert box
           console.log(result['city']) // city in console
        },
        error : function () {
           alert("error");
        }
    });
});

Open in new window


Im very new to ajax so I'm hoping im just overlooking something simple but if there is a better way to do it altogether im open to that too. Thanks!
0
I've got an ajax call that returns the following object:

d:
[{"Name":"Elvis", "Num":"100", "Phone":"Y"},{"Name":"Presely", "Num":"101", "Phone":"N"},{"Name":"Maria", "Num":"103", "Phone":"Y"}]


I'm trying to loop over everything so I can capture the values. The variable that contains this object is json.  I've tried the following code and haven't gotten any where and I'm stuck:
jQuery.each(json, function (i, val) {
  $.each(val, function (j, v) {
            alert( v.Name +  v.Num + v.phone)
                });

Open in new window


Any thoughts?
0
Hi Guys,

I would like to get the property names from a Javascript object to build a table dynamically. Example:

var data = [{
        Name: "xxxx",
        Last: "bbbbb"
                },
{
        Name: "ddddd",
        Last: "sssss"
}]

Now imagine this properties (Name , Last) come in different name from the database so how could I retrieve the property data from the json array with javascript.

Thank.
0
I use twilio api and download the recording below


/2010-04-01/Accounts/ACf071d40db95b8e4d9c206d62b626e6b3/Recordings/REf87ead782e21c8c5fb353992bce20a6dasdfasdfdas.json

How can i make it so I can listen it?
0
I have a function that calls an AJAX request so I can have data returned.  Currently when I step through the code everything works, but when I get to the AJAX it steps over it but my web method (vb.net) does not fire.  I've double and triple checked my ajax url, added async:false, added  error handling, and even added the function inside of the function to try and get this to work.  If I expose the ajax outside of the function everything seems to work fine except it fires when the page loads and not when a button is pressed.


Below is my code:

function writeTable(SectionID, tableid,year) {


    var json = get_Data();
....

Open in new window


function get_Data() {
    $(function () {
        $.ajax({
            type: "Get",
            contentType: "application/json; charset=utf-8",
            url: "Test.aspx/Get_Results",
            data: JSON.stringify(),
            dataType: "json",
            async: "false",
            success: function (response) {
                alert('sucess');
            },

            error: function (jqXHR, exception) {
                var msg = '';
                if (jqXHR.status === 0) {
                    msg = 'Not connect.\n Verify Network.';
                } else if (jqXHR.status == 404) {
                    msg = 'Requested page not found. [404]';
                } else if (jqXHR.status == 500) {
                    msg = 'Internal Server Error [500].';
                } else if (exception === 'parsererror') {
          

Open in new window

0
Stack Overflow Podcast - Frustrating Miracles
Stack Overflow Podcast - Frustrating Miracles

In this podcast, Stack Overflow interviewed Linux Academy CEO/Founder, Anthony James, and got his developer story!

"Follow your passion, be prepared to work hard and sacrifice, and, above all, don't let anyone limit your dreams."  - Donovan Bailey

Hello,
I try out SQL to query a table and get an sorted result. My table is

ID
parent
name
date

1 ; 0 ; "parameter"
3; 1; "names" 
4;3; "name 1"
5;3; "name 2"
6;3;"name 3"
7;5;"name 4"

Open in new window


The ID is an auto increase value. Each ID has one or more parents.
Final I want to get a result that shows me the name of all IDs an their parents parent in JSON.

{
   "first parent": {
      "Second item",
      "third item": {
          "fourth item",
       }
   "fifth item",
   }
}

Open in new window


How looks an SQL Query for this? I have to go much more deeper but I want to learn how to sort a database and make a JSON from it

Thanks,

Ingo
0
The well known Cerber ransomware continues to spread this summer through spear phishing email campaigns targeting enterprises. Learn how it easily bypasses traditional defenses - and what you can do to protect your data.
3
Hi guys,

We are working on an application one of our developers built, he has since left the company, and i am not a developer and i really need some help i have looked at freelancer among others to try and get someone to fix this and i am really desperate, basically we have a music playout system that sits on an ubuntu box, it plays music in accordance with playlists, that are downloaded weekly

The issue we are having at the moment is the pipe to do the writeStream is not working properly on the “finish” event resulting in the box not fully downloading the playlist before it does its check, meaning it gets a false positive when comparing to see if the file is new.

We have also tried listening for “end” and “close”

Same issue with both.

where we have set up the responseStream variable with the on response events.

What we have found is the server does not appear to be giving the request a response – how can we enable the server to send http status code responses then I can use the reponse.statusCode to see if a new file is available and make this whole thing a lot easier and more robust.
0
Hi experts, is there way (util, script, open source/ licensed product) to receive Jason and generate HTML pls?
0
Hi Guys,

We wrote an application that downloads json files down to about 80/90 client machines, we have reworked the mechanism but cant get it work correctly

I want to know how we could enable our server to send http status code responses then I can use the reponse.statusCode to see if a new file is available and make this whole thing a lot easier and more robust.
0
I have a working Jquery modal dialog which includes a form to collect a contacts address. At the top of the form is a drop down list which returns pre-defined addresses and a 'Use Address' button (id="signal).  The user can choose a pre-defined address if they wish and click the 'Use Address' button which takes the address values and pre-populates the form, thereby, saving the user from having to type in the address manually.

The html for modal form is
<div id="addcontact-window" title="Add Agency Contact">
    <div align="center">
    <p id="errors6"></p>
    </div>
    <form id="addcontactForm" name="addcontactForm" action="" method="post">
    <div id="addcontactFormBody"></div> 
    </form>
    </div>

Open in new window


The jquery code which declares/defines the dialog is:

$("#addcontact-window").dialog(
                        {
                        autoOpen: false,
                        maxWidth:850,
                        maxHeight: 700,
                        width: 850,
                        height: 700,
                        draggable: true,
                        modal: true,
                        buttons: {
                          "Save": function () 
                          { 
                          $.post("./add_agencycontact_process.php", $("#addcontactForm").serialize(), function(response)
                            {
                            if(!response)
                            {
                            

Open in new window

0
I have a web part page displaying 5 web parts. Four of the web parts (Efforts, Phases, Capture Points & Areas) are "provider" web parts, and come from lists that are the sources of 4 lookup columns in the 5th "consumer" web part (Lessons Learned).

The provider web parts are displaying the Title column from the lists.

The Using Javascript/jQuery, I "connected" the 4 provider web parts to the consumer web part, such that when you click on a Title column value, the consumer web part is filtered to show only those records that have the clicked value in the relevant metadata column.

All that is working very nicely.

Now, my requirement is to go one step further, and display the number of items that will be displayed if you click on a Title column value in any of the 4 web parts. If there are none, a "0" should be displayed.

I've constructed a lists service query that successfully returns the number of items that exist for a given, hard-coded, metadata value:
[SiteURL]/_vti_bin/listdata.svc/[ListName]/$count?&$filter=Effort/Title eq 'AAA'

So, the goal is to display such an item count beside the corresponding provider web part value, such as:
Efforts web part:
AAA (10) //assuming there are 10 items in the consumer web part tagged with Effort 'AAA'

Now, I'm bumping up against the current limit of my abilities.

I know that I need code (javascript, rest, ajax, json) for each provider web part with looping to cycle through all of the TD cells that have …
0
Oh men,
Im wondering it is a free plugin or some calendar for  an consulting room apointment
its any idea or recomendation if its for free or open source better
regards
0
I am using Javascript, HTML, Json and PHP.  The emails were sending but now they are not.  Any help is appreciated.  Thank you.

www.mediascrubber.com/videos.html


<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
$(function() {
  $("#myform").on('submit', function(e) {
    e.preventDefault();
    $.ajax({
      url: '//jsbin.com/vufeyag.json',
      dataType: 'json',
      data: $("#myform").serialize()
    }).done(function(d) {
      if (d.success==true) {
        $("#myform").hide();
        $("#results").text("Thanks!").show();
      }
    });
  });
});
</script>>

Open in new window


<?php

$webmaster_email = "ds@mediascrubber.com";
$email_address = $_REQUEST['email_address'] ;

function isInjected($str) {
	$injections = array('(\n+)',
	'(\r+)',
	'(\t+)',
	'(%0A+)',
	'(%0D+)',
	'(%08+)',
	'(%09+)'
	);
	$inject = join('|', $injections);
	$inject = "/$inject/i";
	if(preg_match($inject,$str)) {
		return true;
	}
	else {
		return false;
	}
}


if (!isset($_REQUEST['email_address'])) {
header( "Location: $feedback_page" );
}
elseif ( isInjected($email_address) ) {
header( "Location: $error_page" );
}
else {
mail( "$webmaster_email", "Subscruber",
 
   "From: $email_address" );
   

}
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>

Open in new window


<form id="myform" class="form-horizontal" action="send_mail.php" method="post">
				<div class="input-group">
                <input type="text" name="email_address" class="def-input" placeholder="Your Email Here">
                <span class="input-group-btn">
                <button class="btn-form btn" input type="submit">Subscribe</button>
                </span>
                
				</div>
                </form>
                <div id="results" style="display: none;"></div>

Open in new window

0
Free Tool: Port Scanner
LVL 9
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.

Hello

I'm busy on a project where i have read only access to an oracle database.
Got a running webserver (LAMP) with a running OCI8 connection.
I'm trying to get a select query result from the following:

TableA
ID
DOC_ID
Date
Type

TableB
ID
DOC_ID (references tableA)
FILE_NAME
FILE_ID
FILE_TYPE

TableB can contain more then one result for the same DOC_ID.

The goal is to get the data from TableA appended with the results from TableB where the DOC_ID is the same and get them into a JSON format.
Looking like

{
	"data": [{
		"ID": "123456",
		"DOC_ID": "789456",
		"Date": "2/1/2016",
		"Type": "PI",
		"FILE_NAME": [
			"File1.pdf", "File2.docx"
		],
		"FILE_TYPE": [
			"PDF", "DOCX"
		],
		"FILE_ID": [
			"453215", "654687"
		]
	}, {
		"ID": "544569",
		"DOC_ID": "001223",
		"Date": "2/8/2016",
		"Type": "PI",
		"FILE_NAME": [
			"File1.txt"
		],
		"FILE_TYPE": [
			"TXT"
		],
		"FILE_ID": [
			"453215"
		]
	}, {
		"ID": "2225599",
		"DOC_ID": "0148966",
		"Date": "2/1/2017",
		"Type": "PI",
		"FILE_NAME": [
			"File1.xml", "File2.xml", "File3.xml"
		],
		"FILE_TYPE": [
			"XML", "XML", "XML"
		],
		"FILE_ID": [
			"00147788", "00114455", "00113210"
		]
	}]
}

Open in new window


Any advise on how to best go about this is welcome.
0
I have a very simple JSON feed and have been able to parse the feed using the below code. However, when the script gets to the "OFFERS" structure, it won't output the results cause it sees the brackets [ ] and is treating the data as a LIST of objects under OFFERS instead of objects like they would be under normal braces { }. I don't know how to get Coldfusion to properly give me the subitems of OFFERS.  You can easily see the feed using the link I provide also.

<cfoutput>
<cftry>
	<cfhttp url="https://rest.bandsintown.com/artists/spencerkane/events?app_id=day6mgmt&date=2017-08-19" result="httpResult" charset="utf-8" method="get"/>
 	<cfset BITdata = deserializeJSON(httpResult.filecontent)/>
	<cfloop array="#BITdata#" index="post">
		<cfif StructKeyExists(post, "datetime")>
			<cfset event_date = post.datetime>
		<cfelse>
			<cfset event_date = "">
		</cfif>
		<cfif StructKeyExists(post, "venue") and StructKeyExists(post.venue, "name")>
		    <cfset ev_title = post.venue.name>
		<cfelse>
            <cfset ev_title = "">
		</cfif>
		<cfif StructKeyExists(post, "venue") and StructKeyExists(post.venue, "city")>
			<cfset city = post.venue.city>
		<cfelse>
			<cfset city = "">
		</cfif>
		<cfif StructKeyExists(post, "venue") and StructKeyExists(post.venue, "region")>
			<cfset region = post.venue.region>
		<cfelse>
			<cfset region = "">
		</cfif>
		<cfif StructKeyExists(post, "offers[url]")>
		<cfset tickets = post.offers[url]>
			<cfelse>
		<cfset tickets = "">
		

Open in new window

0
In my .net c# project I have two jason like this

Json1
{"WindowsServices":[{"name":"SNMP","statusID":"1","StatusMsg":"Stopped","FullStatus":"SNMP,1"},{"name":"SNMPTRAP","statusID":"1","StatusMsg":"Stopped","FullStatus":"SNMPTRAP,1"}]}

Open in new window


Json2
{"WindowsServices":[{"name":"SNMP","statusID":"4","StatusMsg":"Running","FullStatus":"SNMP,4"},{"name":"SNMPTRAP","statusID":"1","StatusMsg":"Stopped","FullStatus":"SNMPTRAP,1"}]}

Open in new window


I need to compare this to json and get the result of the modified part oly
{"WindowsServices":[{"name":"SNMP","statusID":"4","StatusMsg":"Running","FullStatus":"SNMP,4"}]}

Open in new window



Thank you for your help!!
0
<cfoutput>
<cftry>
	<cfhttp url="https://rest.bandsintown.com/artists/spencerkane/events?app_id=day6mgmt&start_date=2017-01-01" result="httpResult" charset="utf-8" method="get"/>
 	<cfset BITdata = deserializeJSON(httpResult.filecontent)/>
	<cfloop array="#BITdata#" index="post">
		<cfif StructKeyExists(post, "datetime")>
			<cfset event_date = post.datetime>
		<cfelse>
			<cfset event_date = "">
		</cfif>
		<cfif StructKeyExists(post, "venue.name")>
		    <cfset ev_title = post.venue.name>
		<cfelse>
            <cfset ev_title = "">
		</cfif>
		<cfif StructKeyExists(post, "venue.city")>
			<cfset city = post.venue.city>
		<cfelse>
			<cfset city = "">
		</cfif>
		<cfif StructKeyExists(post, "venue.region")>
			<cfset region = post.venue.region>
		<cfelse>
			<cfset region = "">
		</cfif>
		<cfif StructKeyExists(post, "offers.url")>
		<cfset tickets = post.offers.url>
			<cfelse>
		<cfset tickets = "">
			</cfif>

<!--- FEED OUTPUT --->        
<cfif not event_date is "">		
#event_date#<p>
#ev_title#<p>
#city#<p>
#region#<p>
#tickets#
<hr />
</cfif>		
	</cfloop>

	<cfcatch type="any">
		<p>
			<cfdump var="#cfcatch#" />
			#LSDateFormat(Now(), "dd-mm-yyyy")# #lsTimeFormat(Now(), "HH:mm")#<br />
			<a href="##">
				Oh, sorry... I can't connect to Bandsintown
			</a>
		</p>
	</cfcatch>

</cftry>
</cfoutput>

Open in new window


My output only gives me the datetime and none of the other structure data even though the raw feed in a browser window definitely shows there is more data to be displayed. I am using Adobe's output structure of data.struct1.substruct but it doesn't display anything.
0
Oh men,
Im wondering if you guys can give me some advice and examples of how i can position my web page in the proper manner,
some tricks or best practices for positioning my page locally
regards
0
Hi guys,

I seem to be having an issue with my site, where iradio.ie/listen will be hammered after a while, however if i turn on my cloudfare to "I'm under attack" it will work fine but will display a message which in turn deters visitors, i think it is to do with my player here http://iradio.ie/newPlayer but maybe the fact that the iradio app is also pointing to http://iradio.ie/listen to get the audio streams, it is not able to handle the traffic or maybe its just down to poor config?

Any help would be greatly appreciated
0

JSON

502

Solutions

543

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