SAPUI5 access getProperty() of Json Model (undefined). The Model itself is accessible - json

I can't access my JSON model which has been defined in the manifest.json.
My JSON data "zCatsTestJ" looks like this:
{
"d": {
"results": [{
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}, {
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}]
}
}
The model seems to be accesible as sJsonDate1 is showing me the data in the console but I can't access a single date. In the end I want to loop over those dates and change the formatting.
var sJsonDate1 = this.getOwnerComponent().getModel("zCatsTestJ");
var sJsonDate2 =this.getOwnerComponent().getModel("zCatsTestJ").getProperty("/d/results/1/workdate");
console.log(sJsonDate1);
console.log(sJsonDate2);
Here is the console output where I can see the complete data.
Console sJsonDate1
But when I try to access one datapoint it says undefined
Console sJsonDate2
I have also instatiated the Model directly in the component and it is working fine. When I compare the model object from getOwnerComponent() and the new one they are nearly the same except for the local one having no aBindings
Model comparison in console
Any help will be highly apreciated. Thanks

Your JSON is invalid, status is missing " and you never close the array. I tried it locally after correcting your JSON and it worked fine on my end.
var json = {
"d": {
"results": [
{
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}, {
"status": "30",
"skostl": "6210",
"catshours": "2.50",
"ktext": "-",
"counter": "000003484040",
"mandt": "101",
"pernr": "00015822",
"usrid": "-",
"workdate": "\/Date(1477267200000)\/",
"raufnr": "6000025",
}]
}
};
var myModel = new JSONModel(json);
this.getView().setModel(myModel, "test");
this.getView().getModel("test").getProperty("/d/results/1/workdate"); "/Date(1477267200000)/"

Here is the solution. Somehow the JsonModel was too big (667 Data Points) and wasn't loaded on the time of calling it. That's why it has worked with only two entries.
myModel.attachRequestCompleted(function() {
var sJsonDate = myModel.getProperty("/d/results/1/workdate");
console.log(sJsonDate);
});

Related

How to read data from nested JSON structure in protractor

Below is my code and I want to extract data under "specs" part like description, status etc. however I'm getting undefined when I capture the data and print it in the console. I have tried
let web = JSON.parse(jsondata);
let TestSuite = web["suite1"]["description"]
and this is providing data in console however, when I use this,
let id = web["suite1"]["specs"]["id"]
its gives undefined. Please help!
{
"suite1": {
"id": "suite1",
"description": "Login",
"fullName": "Login",
"failedExpectations": [],
"status": "finished",
"specs": [
{
"id": "spec0",
"description": "Should able to login into the Distribution management Webpage",
"fullName": "Login Should able to login into the Distribution management Webpage",
"failedExpectations": [
{
"matcherName": "",
"message": "",
"stack": "",
"passed": false,
"expected": "",
"actual": ""
}
],
"passedExpectations": [],
"pendingReason": "",
"started": "2018-09-06T06:57:42.740Z",
"status": "failed",
"duration": "7 secs",
"stopped": "2018-09-06T06:57:49.255Z",
"browserLogs": []
}
]
} }
JSON.parse(JSON.stringify(json)).suite1.specs[0].id
specs contains an array of objects. First, you need to get the object from the array and then get a value of the object.
Try this:
let id = web["suite1"]["specs"][0]["id"]
OR
let id = web.suite1.specs[0].id
Hope this will work.
When you do ["suite1"]["specs"], you select array. You need an index, which is the 0-th one in this case.
You can check that by typing Object.prototype.toString.call( data["suite1"]["specs"]).
You can try with:
data["suite1"]["specs"][0]["id"]
Or use the object property notation
data["suite1"]["specs"][0].id

get by id from local json http

I have fake users.json file and I can http.get to list the array of json.
Since I want to get the particular user by id and haven't stored the data in the database, instead just use the fake json data.
[
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
I can do this stuff if the data is stored in the database, but not sure how to proceed with the fake json data.
Any help is appreciated.
Thanks
If you need the json as raw data, for just fake data, You can simply require it and use it as object..
const JsonObj = require('path/to/file.json')
console.log(JsonObj[0].id) // <-- cb55524d-1454-4b12-92a8-0437e8e6ede7
Plus, if you need more dynamic solution, there is a good JSON-server you can easily use for testing and so: check this git repo
var _ = require('underscore');
var dummyJson = [
{
"id": "cb55524d-1454-4b12-92a8-0437e8e6ede7",
"name": "john",
"age": "25",
"country": "germany"
},
{
"id": "ab55524d-1454-4b12-92a8-0437e8e6ede8",
"name": "tom",
"age": "28",
"country": "canada"
}
]
var requiredID = "cb55524d-1454-4b12-92a8-0437e8e6ede7";
var reuiredObject = _.find(dummyJson, function (d) {
return d.id === requiredID;
})
Get JSON object using JSON.parse('users.json') and store it in a variable users.
Loop through array of users using for .. in and using if condition on id update the object if required.
Stringify the updated users object using JSON.stringify(users); and write this string to users.json file using fs.write() module in NodeJS so you will have updated objects in your json file.

Python 3.6 - Parse json response with dict inside dict

I'm being driven insane because I can't parse this json response. I've tried many different things and nothing works properly... Could you help me?
The this is the file I am parsing:
{
"info": {
"funds": {
"asset": {
"net": "12516.000",
"total": "0"
},
"borrow": {
"btc": "0",
"cny": "0",
"ltc": "0"
},
"free": {
"btc": "0",
"cny": "0",
"ltc": "0",
"eth": "0"
},
"freezed": {
"btc": "0",
"cny": "0",
"ltc": "0",
"eth": "0"
},
"union_fund": {
"btc": "0",
"ltc": "0"
}
}
},
"result": true
}
I just want something like:
#What I want to get the "net" which is "12516.000", so I tried this:
funds = response['info']['funds']['asset']['net']
funds = response[0] returns { as answer, and funds = response[1] gives me r as a response, and finally if I try funds = response['info'] I get this type error: TypeError: string indices must be integers
You haven't actually parsed the JSON, it's just being read as a string, so response[0] returns the first character of the JSON string, or {. To parse the JSON string,
import json
json.loads(response)['info']['funds']['asset']['net']
which is the pattern you're expecting. More details about the json library can be found here.
I appreciate the answer of #kevmo314.
Sometimes your response may contain leading and trailing whitespaces. You can remove it using strip().
Note: when you get response, basically you get as a string (in some cases, it may be different) which can represent Python objects like list, dictionary etc.
So it's necessary to convert them back into their original form before performing any operations on them.
Below is the working code.
import json
response = response.strip()
response = json.loads(response)
funds = response["info"]["funds"]["asset"]["net"]
print(funds)

Elastic Search + JSON import (ELK Stack)

I'm currently trying to do a basic JSON file import into my ELK stack. I tried importing it directly via a POST request like this:
curl -XPOST http://localhost:9200/kwd_results/TS_Cart -d #/home/local/TS_Cart.json
ES says ok for the import, but when I'm trying to view the logs in Kibanna, they are not indexed by the nodes of the JSON file. I'm guessing I need like a template mapping to view it properly.
My JSON file looks like this:
{
"testResults": {
"FitNesseVersion": "v20160618",
"rootPath": "K1System.CountryDe.DriverFirefox.TestCases.MainFolder.TestVariants.SmokeTests_B2C.TS_Cart",
"result": [
{
"counts": {
"right": "16",
"wrong": "2",
"ignores": "3",
"exceptions": "1"
},
"date": "2017-05-10T00:01:11+02:00",
"runTimeInMillis": "117242",
"relativePageName": "TestCase_1",
"pageHistoryLink": "K1System.CountryDe.DriverFirefox.TestCases.MainFolder.TestVariants.SmokeTests_B2C.TS_Cart.B2CFreeCatalogueOrder?pageHistory&resultDate=20170510000111",
"tags": "de, at"
},
{
"counts": {
"right": "16",
"wrong": "0",
"ignores": "0",
"exceptions": "0"
},
"date": "2017-05-10T00:03:08+02:00",
"runTimeInMillis": "85680",
"relativePageName": "TestCase_2",
"pageHistoryLink": "K1System.CountryDe.DriverFirefox.TestCases.MainFolder.TestVariants.SmokeTests_B2C.TS_Cart.B2CGiftCardOrderWithAdvancePayment?pageHistory&resultDate=20170510000308",
"tags": "at, de"
}
],
"finalCounts": {
"right": "4",
"wrong": "1",
"ignores": "0",
"exceptions": "0"
},
"totalRunTimeInMillis": "482346"
}
}
Basically I would need rootPath to be used as an index, while having the following childs: counts, relativePageName, date and tags. Notice that I have two nodes that are childs of the result[] array.
Any help would be greatly appreciated!
Thank you.
Well, it's one JSON document so Elasticsearch treats it as such.
You'll need to (programmatically) split up the document into the right documents and then you can store them (potentially with one _bulk request).
For the index name:
Must be lowercase, so you'll need to cast that value.
Will you have many different root paths with jut a few docs each? Then you shouldn't make all of them an index since there is an overhead for each one of them (actually the underlying shards).

Parsing json in backbone

prodCollect.fetch({
success: function(collection){
console.log(prodCollect.models.length);
var a =prodCollect.models[1];
console.log(a.attributes);
var y=_(a.attributes).toArray();
console.log(y[0]);
}
});
In variable 'a', I'm getting a model and doing console(a.attributes), I'm getting this:
Object {[{"product_id":"2","product_name":"new product","short_description":"used for training of managers","full_description":"used for training of managers","price":"20000.00","acct_manager":"rahul raja","roles":"Manager,Manager","tags":"abc,def","skills":"abc,abc","clients":"accenture,accenture,Wipro,Google"}]: Object}
Now I am unable to access the properties like 'product_name' and 'price'. I tried converting a.attributes into an array and accessing y[0] but its undefined. 'a.attributes' is an object. So I am unable to access the properties.
I am sending this from server
[
"[{\"program_name\":\"training\",\"products\":\"new product,fdgf\",\"roles\":\"Manager,CEO,random\",\"tags\":\"abc,def\",\"skills\":\"abc,def\",\"clients\":\"accenture,wipro\"},{\"program_name\":\"New progs\",\"products\":\"fdgf,ILead\",\"roles\":\"CEO,Manager,random\",\"tags\":\"abc,def\",\"skills\":\"abc,def\",\"clients\":\"\"}]",
"[{\"product_id\":\"2\",\"product_name\":\"new product\",\"short_description\":\"used for training of managers\",\"full_description\":\"used for training of managers\",\"price\":\"20000.00\",\"acct_manager\":\"rahul raja\",\"roles\":\"Manager,Manager\",\"tags\":\"abc,def\",\"skills\":\"abc,abc\",\"clients\":\"accenture,accenture,Wipro,Google\"}]"
]
so variable 'a' contains the second array
I think that the problem came from the server, your log should be like :
{
"product_id": "2",
"product_name": "new product",
"short_description": "used for training of managers",
"full_description": "used for training of managers",
"price": "20000.00",
"acct_manager": "rahul raja",
"roles": "Manager,Manager",
"tags": "abc,def",
"skills": "abc,abc",
"clients": "accenture,accenture,Wipro,Google"
}
Here is an example that illustrate what I suspected your server doing.
So as I suspected, your problem came from the server. Your server response should be like that :
[
{
"product_id": "2",
"product_name": "new product",
...
},
{
"product_id": "2",
"product_name": "new product",
...
},
...
]