IBM Worklight Adapter parsing JSON - json

{
"isSuccessful": true,
"resultSet": [
{
"name": "pradeep",
"password": 123,
"timestamp": "2014-04-08T12:58:45.000Z"
},
{
"name": "dileep",
"password": 1234,
"timestamp": "2014-04-08T13:00:52.000Z"
}
]
}
This invocation result i have got by using Sql adapter so how to parse this invocation result and how can i display name,password,timestamp from this JSON object.Do i need to use HTTP Adapter.

If you want to get the length of results you should use result.invocationResult.resultSet.length which will give you the total number of results, where items is the response coming from the adapter and invocationResult contains the results and other paramaters, from which you will have to access the results for accessing only the particular output.To get value call
result.invocationResult.resultSet.name[position]
Like that call all the fields password,timestamp with position
in for loop
function handleSuccess(result) {
var invocationResult = result.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
var result = invocationResult.resultSet;
for ( var i = 0; i < result.length; i++) {
alert(result.name[i]);
alert(result.password[i]);
alert(result.timestamp[i]);
}
} else {
alert("error");
}

Related

How to access data inside a complex JSON object in Dart?

I use a WebSocket to communicate to a server in my Flutter app. Let's say I receive a JSON object trough the WebSocket :
{
"action": "getProduct",
"cbackid": 1521474231306,
"datas": {
"product": {
"Actif": 1,
"AfficheQte": 0,
"Article": "6"
},
"result": "success"
},
"deviceID": "4340a8fdc126bb59"
}
I have no idea what the content of datas will be until I read the action, and even then, it's not guaranteed to be the same every time. One example of a changing action/datas is when the product doesn't exist.
I can parse it in a Map<String, Object>, but then, how do I access what's inside the Object?
What's the correct way to read this data?
Not sure what the question is about, but you can check the type of the values and then continue accordingly
if(json['action'] == 'getProduct') {
var datas = json['datas'];
if(datas is List) {
var items = datas as List;
for(var item in items) {
print('list item: $item');
}
} else if (datas is Map) {
var items = datas as Map;
for(var key in items.keys) {
print('map item: $key, ${items[key]}');
}
} else if(datas is String) {
print('datas: $datas');
} // ... similar for all other possible types like `int`, `double`, `bool`, ...
}
You also can make that recursive to check list or map values if they are String, ...

DocumentDB: bulkImport Stored Proc - Getting 400 Error on Array/JSON issue

I'm simply trying to execute the standard example bulkImport sproc for documentDB API and I can't seem to pass it an array of objects. I always get 400 errors despite the documentation giving clear direction to send an array of objects
.. very frustrating.
Additional details: Even if I wrap the array in an object with the array under a property of 'items' and include it in my sproc it still errors out saying the same bad request, needs to be an object or JSON-serialized. When I try to do JSON.stringify(docs) before sending it fails to parse on the other side.
Bad Request: The document body must be an object or a string representing a JSON-serialized object.
bulkInsert.js:
https://github.com/Azure/azure-documentdb-js-server/blob/master/samples/stored-procedures/BulkImport.js
My Code (using documentdb-util for async):
execProc(docs, insertProc);
async function execProc(docs, insertProc){
let database = await dbUtil.database('test');
let collection = await dbUtil.collection(database, 'test');
let procInstance = await dbUtil.storedProcedure(collection, insertProc);
try{
let result = await dbUtil.executeStoredProcedure(procInstance, docs);
console.log(result);
} catch(e){
console.log(e.body)
}
}
Header
Object {Cache-Control: "no-cache", x-ms-version: "2017-11-15",
User-Agent: "win32/10.0.16299 Nodejs/v8.9.0 documentdb-nodejs-s…",
x-ms-date: "Mon, 11 Dec 2017 07:32:29 GMT",
Accept:"application/json"
authorization: myauth
Cache-Control:"no-cache"
Content-Type:"application/json"
User-Agent:"win32/10.0.16299 Nodejs/v8.9.0 documentdb-nodejs-sdk/1.14.1"
x-ms-date:"Mon, 11 Dec 2017 07:32:29 GMT"
x-ms-version:"2017-11-15"
Path
"/dbs/myDB/colls/myColl/sprocs/myBulkInsert"
Params
Array(3) [Object, Object, Object]
length:3
0:Object {id: "0001", type: "donut", name: "Cake", …}
1:Object {id: "0002", type: "donut", name: "Raised", …}
2:Object {id: "0003", type: "donut", name: "Old Fashioned", …}
[{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.35
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.25
}]
The "docs" must be an array of array of params, otherwise, the procedure executor will treat them as multiple params of the procedure, not a single-array-param.
the following code works when call storedProcedure to pass argument with array type.
JS:
var docs = [{'id':1},{'id':2}];
executeStoredProcedure(proc, [docs])
C#
var docs = new[] {new MyDoc{id=1, source="abc"}, new MyDoc{id=2, source="abc"}];
dynamic[] args = new dynamic[] {docs};
ExecuteStoredProcedureAsync<int>(
procLink,
new RequestOptions {PartitionKey = new PartitionKey("abc")},
args);
NOTE: you must ensure the 'docs' have the same partition key, and pass partion key in RequestionOptions
I had the same problem. I was able to get it to work by Stringify the Array and parse it in the stored procedure. I opened an issue on the github where that code originated as well. Below is what worked for me. Good luck.
---- Stringify Array
var testArr = []
for (var i = 0; i < 50; i++) {
testArr.push({
"id": "test" + i
})
}
var testArrStr = JSON.stringify(testArr)
//pass testArrStr to stored procedure and parse in stored procedure
---- Slightly altered original BulkImport
exports.storedProcedure = {
id: "bulkImportArray",
serverScript:function bulkImportArray(docs) {
var context = getContext();
var collection = context.getCollection();
var docsToCreate = JSON.parse(docs)
var count = 0;
var docsLength = docsToCreate.length;
if (docsLength == 0) {
getContext().getResponse().setBody(0);
}
var totals = ""
function insertDoc(){
var msg = " count=" + count+" docsLength=" +docsLength + " typeof docsToCreate[]=" + typeof docsToCreate+ " length =" + docsToCreate.length
if(typeof docsToCreate[count] != 'undefined' ) {
collection.createDocument(collection.getSelfLink(),
docsToCreate[count],
function (err, documentCreated) {
if (err){
// throw new Error('Error' + err.message);
getContext().getResponse().setBody(count + " : " + err);
}else{
if (count < docsLength -1) {
count++;
insertDoc();
getContext().getResponse().setBody(msg);
} else {
getContext().getResponse().setBody(msg);
}
}
});
}else{
getContext().getResponse().setBody(msg);
}
}
insertDoc()
}
}
If you want to test it in the portal Script Explorer I had to create an escaped string i.e.
var testArr = []
for(var i=200; i<250; i++){
testArr.push({"id":"test"+i})
}
var testArrStr = JSON.stringify(testArr)
console.log('"'+testArrStr.replace(/\"/g,'\\"') + '"')

postgresql build_json_object returns

postgesql returns the json_build_object as a parent for each grouped json array like this:
{
"status": "success",
"stories": [{
"json_build_object": {
"CNN": []
}
},
{
"json_build_object": {
"FOX": []
}
},
{
"json_build_object": {
"Huffpost": []
}
},...
Postgresql returns the "json_build_object" as a key.
Is it possible to replace with the stories.source value returned by the group by?
SELECT json_build_object(source, json_agg(stories.*))
FROM stories
GROUP BY stories.source
ORDER BY source;
Optimal solution would be a response like this:
stories:
CNN: [],
FOX: []...
I'm sure I'm missing a best practice for returning JSON in Postgresql...
There must be a way to do this in SQL, but for the lack of it now, you can convert that stories property into the right object:
function convert(stories) {
const res = {};
for (let i = 0; i < stories.length; i++) {
const obj = stories[i].json_build_object;
const name = Object.keys(obj)[0];
res[name] = obj[name];
}
return res;
}

Mongo: Move json string to a part of the document

I have a mongo collection where documents have aprox the following structure:
item{
data{"emailBody":
"{\"uniqueKey\":\" this is a stringified json\"}"
}
}
What I want to do is to use 'uniqueKey' as an indexed field, to make an "inner join" equivalant with items in a different collection.
I was thinking about running a loop on all the documents -> parsing the json -> Saving them as new property called "parsedEmailBody".
Is there a better way to handle stringified json in mongo?
The only way is to loop through the collection, parse the field to JSON and update the document in the loop:
db.collection.find({ "item.data.emailBody": { "$type": 2 } })
.snapshot().forEach(function(doc){
parsedEmailBody = JSON.parse(doc.item.data.emailBody);
printjson(parsedEmailBody);
db.collection.updateOne(
{ "_id": doc._id },
{ "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
);
});
For large collections, leverage the updates using the Bulk API:
var cursor = db.collection.find({ "item.data.emailBody": { "$type": 2 } }).snapshot(),
ops = [];
cursor.forEach(function(doc){
var parsedEmailBody = JSON.parse(doc.item.data.emailBody);
ops.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": { "$set": { "item.data.parsedEmailBody": parsedEmailBody } }
}
});
if (ops.length === 500) {
db.collection.bulkWrite(ops);
ops = [];
}
});
if (ops.length > 0) { db.collection.bulkWrite(ops); }

JSON.net parsing of dynamic JSON

I have JSON that looks like this:
{
"status": {
"code": 0,
"message": "OK"
},
"data": {
"_idtype": "cusip",
"_id": "00768Y883",
"api": {
"_name": "PortfolioBreakdownsRaw",
"PortfolioDate": "2015-10-12",
"GlobalBondSuperSectorLongSalePositionBreakdown": [
{
"Name": "Municipal",
"Value": "0.57842"
},
{
"Name": "Corporate",
"Value": "1.79649"
},
{
"Name": "Securitized",
"Value": "5.29493"
},
{
"Name": "Cash & Equivalents",
"Value": "166.20776"
}
],
"GlobalBondSuperSectorShortSalePositionBreakdown": [
{
"Name": "Government",
"Value": "0.90557"
}
]
}
}
}
I am able to get the api portion of the response easily:
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
From here, I don't what if any arrays will be included in the response. The ultimate goal will be to create a parser that will be able to get the array names (GlobalBondSuperSectorShortSalePositionBreakdown) and as many rows of key-value pairs that it may contain, without first knowing the names such as (GlobalBondSuperSectorShortSalePositionBreakdown) beforehand.
I can't seem to find a good way to loop through the object, determine there are arrays at the api level and then iterate through those to get the values.
Any help would be appreciated.
Here's an example. In this code, the api variable holds a JObject, so we can iterate over its properties. From there, we look at the Type of each property value to see if it is an array or not. If it is, then we can iterate over that array to get the JObjects within it, and extract the Name and Value values that we expect to find there. Does this help?
var jObject = JObject.Parse(json);
var api = jObject["data"]["api"];
foreach (JProperty prop in api.Children<JProperty>())
{
JToken value = prop.Value;
if (value.Type == JTokenType.Array)
{
Console.WriteLine(prop.Name + ": ");
foreach (JObject jo in value.Children<JObject>())
{
Console.WriteLine(" " + jo["Name"] + ": " + jo["Value"]);
}
}
else
{
Console.WriteLine(prop.Name + ": " + value);
}
}
Output:
_name: PortfolioBreakdownsRaw
PortfolioDate: 2015-10-12
GlobalBondSuperSectorLongSalePositionBreakdown:
Municipal: 0.57842
Corporate: 1.79649
Securitized: 5.29493
Cash & Equivalents: 166.20776
GlobalBondSuperSectorShortSalePositionBreakdown:
Government: 0.90557
Fiddle: https://dotnetfiddle.net/XyoXQy
With Linq you can play pretty nice with Json.net:
Here is an easily readable version of the chunk of code that will create two dictionaries out of the JArray properties under the api element:
var api = jObject["data"]["api"];
var arrays = api.Cast<JProperty>().Where(o => o.Value.Type == JTokenType.Array).Select(token => token.Value).ToArray();
var dictionaries = new List<Dictionary<string, string>>();
foreach (var array in arrays)
{
var dictionary = array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>());
dictionaries.Add(dictionary);
}
alternative:
The same thing, but a shorter, more compact version :
var api = jObject["data"]["api"];
var dictionaries = api
.Cast<JProperty>()
.Where(o => o.Value.Type == JTokenType.Array)
.Select(token => token.Value)
.Select(array => array.ToDictionary(token => token["Name"].Value<string>(), token => token["Value"].Value<string>()));