Return JSON from XQuery?
As far as I can tell there is no support to return data from a query in the JSON format? I tried to generate JSON data myself but because of all these nested calls of string-join(), concat(), string() etc. the code is hardly readable. Anything else I could try apart from converting XML to JSON on the client side?
Boris
I think others have implemented XML-to-JSON conversions before. It seems, however, that there is no 1-to-1 mapping from XML to JSON. You might still want to take a look at XSLT and the FXSL/JSON library by Dimitre Novatchev.
Michael Ludwig
Similar Messages
-
Incorrect type inferrence when returning JSON from a cfc?
So, I have a CF function inside a cfc file that queries my
SQL database and then returns the CF query object. One of the
database fields is an nvarchar field contains a bunch of check
numbers, some of which have leading zeros.
The example I have used is a field containing the string
"02":
If I use cfdump, it shows up correctly as 02.
If I call the cfc directly from my browser and ask it for
wddx, I get the correct result <field
name='CHECKNUMBER'><string>02</string></field>
If I call the cfc directly from my browser and ask for json,
I get 2.0 back. WRONG.
Is CF8 just naively guessing the datatype when is does JSON
serialization? CF query objects have types in them and it does it
correctly in the other two cases so it obviously has the correct
type information available. I ended up retrieving WDDX instead of
JSON and deserializing it into a Javascript object using the
wddxDes.js file from www.openwddx.org. I also find it strange and
annoying that the matching wddx.js file from the same web site is
included with the standard installation of Coldfusion but the
deserializer part is not. Has anyone else run into these problems
or found a solution that works without extending Coldfusion with
outside help? This just seems like a straight-up bug in CF8 to
me.> If I call the cfc directly from my browser and ask for
json, I get 2.0 back.
> WRONG.
> [...]
>This just seems like a straight-up bug
> in CF8 to me.
Agreed.
This can be easily demonstrated with this code:
<cfscript>
q = queryNew("col1", "CF_SQL_VARCHAR");
queryAddRow(q);
querySetCell(q, "col1", javacast("String", "02"));
j = serializeJson(q);
writeOutput(j);
</cfscript>
This outputs:
{"COLUMNS":["COL1"],"DATA":[[2.0]]}
If one changes the string to " 20", it outputs:
{"COLUMNS":["COL1"],"DATA":[[" 02"]]}
So it's definitely not paying attention to the data-type of
the string. CF
has a habit of mucking things up like this.
I think you should raise a bug with Adobe.
Adam -
Return data from Java servlet in form of JSON encoded parameters in Javascr
How to return data from Java servlet in form of JSON encoded parameters in Javascript handler function call?
The same is implemented in php as the following
echo "sT.handleAjaxResponse(";
echo json_encode($response);
echo ");";
How to do the same in Java servlet?
Thanks.With the rising popularity of JSON (especially with Ajax), support for it has started to appear in the Java community. I am not aware of any standardized approach yet, but expect it is likely we'll see that eventually. For now, you probably want to look at a third-party library such as the [JSON in Java Library|http://www.json.org/java/], Jettison, or [Java Tools for the JSON Format|http://jsontools.berlios.de/].
-
Populating a drop down list of users using JSON from a REST call
Hi guys,
First post, have just started the mammoth project of turning us paperless.
My first task has been to create a header template - this header to be used on any form we use. I got this done almost without issue, it seems the only complication is to attach the username to the document.
Initially I tried to do this with a text field. I set this up with a calculation script to set this.rawValue = identity.username (also tried identity.name), however further reading taught me that that requires priviledged context (haven't figured out what that is or how to get it yet, but it seems like a 'no' for this method).
My next step has been to attempt to let the user pick their username from a list. "Easy!" I thought, "I just set up a webscript last week to return a configurable list of user details. My web script (it runs off of Alfresco CMS, for the record) is accessed from an URL like https://docs.ourcompany.com:8443/alfresco/service/ourcompany/users?useGroup=[a user group]&filter=[a filter string] and returns JSON like this:
"users" :
"name" : "Chris O'Kelly", "userName" : "ChrisO"
"filter" : "all",
"error" : 0
In the layout:ready script section for my dropdown I have used the following js
function createRequest() {
var result = null;
if (window.XMLHttpRequest) {
// FireFox, Safari, IE>6
result = new XMLHttpRequest();
if (typeof xmlhttp.overrideMimeType != 'undefined') {
result.overrideMimeType('application/json');
else if (window.ActiveXObject) {
// IE <7
alert("No available type");
result = new ActiveXObject("Microsoft.XMLHTTP");
else {
alert("No available type");
return;
return result;
var req = createRequest();
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if (req.status != 200) {
alert("REST call failed");
return;
// Request successful, read the response
var resp = req.responseText;
this.addItem(resp.users.name, resp.users.userName);
req.open("GET", "https://docs.ourcompany.com:8443/alfresco/service/ourcompany/users?useGroup=GROUP_EveryUser&filter=status", true);
req.send();
But when I preview the form I get nothing, no errors, no alerts, no filling of the dropdown. I've read a few conflicting forum posts on whether or not xmlHttpRequest works within liveCycle forms, so I suppose the guts of my question boils down to- does it?Hi!
In the DropDownList set the labelField property to the name of the object property you want to appear.
Ex:
<s:DropDownList labelField="facilityNumber"
includeIn="NewInspection"
dataProvider="{ddFacNum}"
fontFamily="Arial" fontSize="16"
id="ddFacilityNumber"
prompt="Select facility number..."/> -
How to include CDATA in xml generated from XQuery
I need to include Cdata in the xml generated from my xquery which is given below:
I tried using XMLCDATA, but not getting the desired output. What am I doing wrong?
SELECT XMLQuery('<InsUpdDel>
for $crv in ora:view("RELATION")
return
<first>
<eff_date>{$crv/ROW/EFF_DATE/text()}</eff_date>
<source>{$crv/ROW/SOURCE/text()}</source>
<key>
<fld>
<id>from_type</id>
<val>XMLCDATA({$crv/ROW/FROM_ENT_TYPE/text()})</val>
</fld>
<fld>
<id>from_ent_id</id>
<val>{$crv/ROW/FROM_ENT_ID/text()}</val>
</fld>
</key>
</first>}</InsUpdDel>'
RETURNING CONTENT)
FROM dual;
The output I get is XMLCDATA(C), while the desired output is <![CDATA[C]]>Forgive me my vanity to think I can contribute by kicking doors open that are probably already wide open....I might create more confusion, but perhaps it helps some of the readers of this thread....
In general it is not such a good idea to use "string" functions to create (serialized) XML. XML tools (including Oracle XML DB) go through a lot of effort to make sure that when a "native" XML structure is serialized to a string, the XML rules are strictly obeyed (e.g. special character escaping).
Just assume e.g. that the $i/Reference from above contains something like ]]><
The resulting XML would not be valid.
More info on serializing XML in the context of XQuery is available from
- http://www.w3.org/TR/xquery/#id-serialization
- http://www.w3.org/TR/xslt-xquery-serialization/
- http://www.w3.org/TR/xslt-xquery-serialization/#XML_CDATA-SECTION-ELEMENTS
Unfortunately I do not think Oracle XML DB currently implements these parts of the spec (perhaps 11g will)...leaving the OP's question unanswered.
Anyway, if going the route of serializing the XML through string functions, it is always good to realize the dangers of such an approach.
Peter -
XmlHttpRequest AJAX not returning message from COMET server
I have the following COMET client javascript code:
function getResponse() {
document.getElementById("_receivedMsgLabel").innerHTML += "getResponse() called.<br/>";
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", "http://L45723:1802?callback=testcallback", true); //must use this URL at work.
receiveReq.onreadystatechange = handleReceiveMessage;
alert("handleReceiveMessage assigned to onreadystatechange event.");
receiveReq.overrideMimeType("text/x-json");
receiveReq.timeout = 100000;
var currentDate = new Date();
var sendMessage = JSON.stringify({
SendTimestamp: currentDate,
Message: "Message 1",
Browser: navigator.appName,
OriginUrl: document.URL
var sendMessage = "SendTimestamp=" + currentDate + "&Message=Message1&Browser=" + navigator.userAgent;
alert("JSON message created. About to send...");
receiveReq.send(sendMessage);
alert("Message sent.");
//function for handling the return message from Comet
function handleReceiveMessage() {
document.getElementById("_receivedMsgLabel").innerHTML += "Status=" + receiveReq.status;
document.getElementById("_receivedMsgLabel").innerHTML += "responseText=" + receiveReq.responseText;
if (receiveReq.readyState == 4 && receiveReq.status == 200) {
document.getElementById("_receivedMsgLabel").innerHTML += "Message received!<br/>";
var status = receiveReq.status;
var txt = receiveReq.responseText;
document.getElementById("_receivedMsgLabel").innerHTML += txt + "<br/>";
mTimer = setTimeout("getResponse();", 0);
getResponse();
The GET request is sent and received by the COMET server, which sends the response back when I choose to. The handleReceiveMessage() function is called, but the message the server sent is not in the xmlHttpRequest.responseText property.
Why?I suggest continuing the discussion in your thread on mozillaZine, since this site focuses more on end-user support.
[http://forums.mozillazine.org/viewtopic.php?f=25&t=2480435 xmlHttpRequest object - mozillaZine Forums] -
Return XML from MVC WebAPI Web Service
The tutorials to create a web service using MVC WebAPI (frmaework4.5) in VS 2013 is touted as being "very simple" to return JSON or XML.
But then, all you get is JSON. When you want to return a plain ole' string of XML ... there is no clear documentation. I see a bunch of posts where people are referencing the ActionResult method ... which is not in the APIController class... so that implies
to me that I need to roll my own from the Controller class. That doesn't seem right to me.
So ... how does one return an XML string from an MVC WebApi application?
* the list of "questions similar to yours" that this forum presents me either: a) are for ASMX in VS 2008 or b) do not work.
Any direction to some documentation is appreciated.
ThanksHi,
If this issue is related to MVC, you could ask this question in the ASP.NET forum:
http://forums.asp.net. If then, you could get an answer more quickly and professional. Maybe the
WCF, ASMX and other Web Services forum will be better for this issue. Thanks for your cooperation.
Have a nice day,
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Ajax call method which return json Data
Hi, I make one function , which i want to return json value , for this which return type i mention in function:
This is javascript which call Retrieve method.
<script>
debugger;
var remoteDatasource = new kendo.data.DataSource({
transport: {
read: {
type:"POST",
url: "Controllers/Home.cfc",
dataType: "json",
data: {
method: "Retrieve",
dataLists: JSON.stringify(request)
</script>
Home.cfc
component
remote function Retrieve(string dataLists)
try
q = new Query();
q.setsql("SELECT * FROM Product");
qResult = q.execute().getresult();
col_len = ListLen(qResult.Columnlist);
dataArray = ArrayNew(1);
row = 0;
col = 0;
for(row = 1; row <= len; row++)
for(col = 1; col <= col_len; col++)
FieldName = ListGetAt(qResult.Columnlist, col);
dataArray[row][col] = qResult[FieldName][col];
jsonvar=serializeJSON(dataArray);
catch(any e)
return jsonvar;One can see immediately that you have to make the following corrections, at least:
Give the query a name;
Point the query to a datasource;
Define the variable 'len' (even better, use a different, less confusing, name for the variable). -
How to get return value from java and read by other application?
i want to read return value from java and the other application read it.
for example:
public class test_return {
test_return(){
public int check(){
return 1;
public static void main(String args[]){
new test_return().check();
}from that class i make as jar file. How to read the return value (1) by other application?
thx..If your installer is requiring some process it invokes to return a particular value on failure, then the installer is seriously broken. There are a bazillion commands your installer could invoke, and any of them could fail, which in turn could invalidate the entire install process, and any of them could return any value on failure. The only value that's consistent (in my experience) is that zero means success and non-zero means failure, with specific non-zero values being different in different programs.
About the only control you have over the JVM's exit code is that if your main method completes without throwing an exception, the JVM will have an exit code of 0, and if main throws an exception (either explicitly or by not catching one thrown from below), it will be non-zero. I'm not even sure if that's guaranteed, but I would guess that's the case.
EDIT: I'm kind of full of crap here. If you're writing the Java code, you can call System.exit(whatever). But nonetheless, if your installer requires certain exit codes from any app--java or otherwise--you have a problem.
Edited by: jverd on Oct 29, 2009 1:27 AM -
How to get return value from Java runtime.getRuntime.exec?
I'm running shell commands from an Oracle db (11gr2) on aix.
But, I would like to get a return value from a shell comand... like you get with "echo $?"
I use a code like
CREATE OR REPLACE JAVA SOURCE NAMED common."Host" AS
import java.io.*;
public class Host {
public static int executeCommand(String command) {
int retval=0;
try {
String[] finalCommand;
finalCommand = new String[3];
finalCommand[0] = "/bin/sh";
finalCommand[1] = "-c";
finalCommand[2] = command;
final Process pr = Runtime.getRuntime().exec(finalCommand);
pr.waitFor();
catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
retval=-1;
return retval;
/but I do not get a return value... because I don't know how to get return value..
Edited by: user9158455 on 22-Sep-2010 07:33Hi,
Have your tried pr.exitValue() ?
I think you also need a finally block that destroys the subprocess
Regards
Peter -
How to get the return values from a web page
Hi all :
how to get the return values from a web page ? I mean how pass values betwen webflow and web page ?
thank you very much
Edited by: jingying Sony on Apr 15, 2010 6:15 AM
Edited by: jingying Sony on Apr 15, 2010 6:18 AMHi,
What kind of web page do you have? Do you have possibility to for example make RFCs? Then you could trigger events (with parameters that could "return" the values) and the workflow could react to those events. For example your task can have terminating events.
Regards,
Karri -
Remote Object - not able to get the returned value from java method
Hi ,
I am developing one sample flex aplication that connects to the java code and displays the returned value from the
java method in flex client. Here I am able to invoke the java method but not able to collect the returned value.
lastResult is giving null . I am able to see the sysout messages in server console.
I am using flex 3.2 and blazeds server and java 1.5
Here is the code what I have written.
<?xml version="1.0" encoding="utf-8"?><mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" backgroundColor="#FFFFFF" initialize="initApp()">
<mx:Script><![CDATA[
import mx.controls.Alert;
import mx.binding.utils.ChangeWatcher;
import mx.rpc.events.ResultEvent;
import mx.messaging.*;
import mx.messaging.channels.*
public function initApp():void {
var cs:ChannelSet = new ChannelSet();
var customChannel:Channel = new AMFChannel("my-amf", "http://localhost:8400/blazeds/messagebroker/amf"); cs.addChannel(customChannel);
remoteObj.channelSet = cs;
public function writeToConsole():void { remoteObj.writeToConsole(
"hello from Flash client");
var returnedVal:String = remoteObj.setName().lastResult; Alert.show(returnedVal);
//[Bindable]
// private var returnedVal:String;
]]>
</mx:Script>
<mx:RemoteObject id="remoteObj" destination="sro" />
<mx:Form width="437" height="281">
<mx:FormItem>
</mx:FormItem>
<mx:Button label="Write To Server Console" click="writeToConsole()"/>
</mx:Form>
</mx:WindowedApplication>
Java code
public
public SimpleRemoteObject(){
super(); }
class SimpleRemoteObject {
public void writeToConsole(String msg) { System.out.println("SimpleRemoteObject.write: " + msg); }
public String setName(){ System.
out.println("Name changed in Java");
return "Name changed in Java";
And I have configured destination in remote-config.xml
<destination id="sro">
<properties>
<source>SimpleRemoteObject</source>
<scope>application</scope>
</properties>
</destination>
Please help me .You are not able to get the returned value because if you see the Remote object help you will realise you have to use result="resultfn()" and fault = "faultfn()"
In this you define what you wish to do.
More importantly in the remote object you need to define which method you wish to call using the method class like this
<mx:RemoteObject id="remoteObj" destination="sro" result="r1" fault="f1" >
<Method name="javaMethodName" result="r2" fault="f2"/>
<mx:RemoteObject>
r2 is the function where you get the result back from java and can use it to send the alert. -
Help with returning query from loadURL()
I finally came across loadURL() and figured out that I can
use it to invoke my ColdFusion components without page
reloading--very handy!
Now, I need to figure out how to do this to return values
from my components. Has anyone done this and have an example I
could see, or at least point out to me a suggestion of code for
successfully doing this?
Right now, my component looks like this:
<cfcomponent output="no">
<cffunction name="getComments" access="remote"
output="no" returntype="query">
<cfset var rsComments = "">
<cfquery name="rsComments" datasource="xmlTest">
SELECT *
FROM comments
ORDER BY commenter DESC
</cfquery>
<cfreturn rsComments>
</cffunction>
</cfcomponent>
I am trying to use loadURL() as follows:
function myQuery() {
var myDatasetURL = 'xmlTest.cfc?method=getComments';
var req = Spry.Utils.loadURL("GET", myDatasetURL, true);
In Firebug, the "Response" shows a serialized WDDX packet.
I've not really messed with these before, so any help would be
greatly appreciated!
Thanks
JoelYour first mistake was to choose an array. An array has a fixed length, so it's not appropriate for storing a sequence whose length you don't know in advance. You should choose a List instead; an ArrayList would be a reasonable implementation to choose.
Then you just add the Point to the ArrayList. Here's how you declare it:
List<Point> points = new ArrayList<Point>();and here's how you use it in the listener:
points.add(evt.getPoint());Returning anything from the listener to its caller, which is something buried in the GUI hierarchy, would be... um... pointless. -
How to get return values from stored procedure to ssis packge?
Hi,
I need returnn values from my stored procedure to ssis package -
My procedure look like and ssis package .Kindly help me to oget returnn value to my ssis package
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [TSC]
-- Add the parameters for the stored procedure here
@P_STAGE VARCHAR(2000)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
--SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2>
truncate table [INPUTS];
INSERT
INTO
[INPUTS_BASE]
SELECT
[COLUMN]
FROM [INPUTS];
RETURN
END
and i am trying to get the return value from execute sql task and shown below
and i am taking my returnn value to result set variableYou need to have either OUTPUT parameters or use RETURN statement to return a value in stored procedures. RETURN can only return integer values whereas OUTPUT parameters can be of any type
First modify your procedure to define return value or OUTPUT parameter based on requirement
for details see
http://www.sqlteam.com/article/stored-procedures-returning-data
Once that is done in SSIS call sp from Execute SQL Task and in parameter mapping tabe shown above add required parameters and map them to variables created in SSIS and select Direction as Output or Return Value based on what option you used in your
procedure.
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Return data from all columns apart from a certain data type.
Bit stuck on something, hope somebody here can help:
I want to do a 'select * from ' a table, to return all columns except ones of a certain datatype. ie. I want to return data from all columns, excluding columns of datatype 'SDO_GEOMETRY'.
This gives me the list of columns:
SELECT COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'ORDER_ITEM'
AND DATA_TYPE <> 'SDO_GEOMETRY'; But I can't seem to take it any further...
Now if I knew the columns beforehand, then of course I could just list them, excluding the geometry column, but this is to be used for a plug-in for MS Word, where a user can pick database columns to dynamically fill a report from - but I don't want the geometry columns as these can't be handled in this way.Hi Reggie,
> connects to the database and presents a list of tables
My guess is that this macro is written so it selects from all_tab_cols.
Change that plugin and let it select from a view like the one above. That way, the users won't be able to see/pick anything that you are not able/willing to present for them.
Edit:
You could even tease your users, and let them see the columns, but not being able to pick them.
create or replace view available_tab_columns
as
select decode(pickable.data_type, null, 0, 1) pickable
,atc.* -- narrow down yourself
from all_tab_cols atc -- or maybe user_tab_cols
,(select 'CHAR' data_type from dual union all
select 'DATE' from dual union all
select 'NUMBER' from dual
-- complete positive list, yourself
) pickable
where atc.data_type = pickable.data_type(+);Regards
Peter
Message was edited by:
Peter Gjelstrup
Maybe you are looking for
-
Can someone please explain and help me? I am unlocking an iphone4 from at&t to use it on the straight talk network. They've confirmed my request to do this and I am now a little confused as to what to do next. They want me to back up the phone using
-
How do I share files between OS Macs on non-apple wireless network?
Hello: We have two iBook G4s, one with 10.4.4, and the other with 10.3.x. When they are connected via hard cable ethernet, they see each other and can share files. But when connected via wireless, they cannot see each other. What do we do? Thanks!
-
ORA-00922: missing or invalid option in create seq, trigger
Hi All, I am trying to create a table, sequence, and trigger with the following SQL and am getting the error: ORA-00922: missing or invalid option CREATE TABLE "DATA_INVENTORY" ( "ID" INTEGER NOT NULL ENABLE, "COE_CONTRACT_NUM" VARCHAR2(30),
-
Diable special keys in projector
is there a way to make the projector ignor '.' (full stop) - so not to jump into my next scene, when I don't want it to? I have a keyboard listener, but according to a trace, the action of the '.' happens before the listener even knows the key is pre
-
SQL*Modeler forgets check constraint names
SQL*Modeler Version 2.0.0. Build 584 If I create named check constraints under the Relational Model/Tables/Table level Constraints then generate the model I have the constraints correctly named. Exit the model and reload, the constraints appear to be