Why doesn't the json model's odata property have columns? - json

I am creating a JSON model in UI5 from a json object. But it is missing the columns array in the JSON model. I checked the model in the console and the odata property had no columns. Check image for proof.
https://ibb.co/hLmYpZb
Hence I want to know how I can get the column to show up.
Here is my code.
var emptyModel = {
"columns": []
};
this.setModel(new JSONModel(JSON.stringify(emptyModel)), "selcontent");
I expect column to show up in the JSON model under the odata property.

JSONModel awaits a plain object or a URL string as the first argument.
Either the URL where to load the JSON from or a JS object (source)
The result of the stringified emptyModel is "{"columns":[]}" which is neither an object nor a URL.

Related

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

Display JSON Object from console

I have a JSON object returned in my console, and I want to display those data named "offers".
the JSON object is returned like that :
I tried to display my JSON Object data with :
console.log(JSON.stringify(data));
The thing is, it says that "data is not defined"
Does anyone know what happens ? :)
You should add full path to element of json, for example if your json looks like:
var json = {"par":22, "par2":555, "elems":[{"attr1":53, "attr2":99}] };
and if you want to get attr1 value, you should do something like this:
console.log(json.elems[0].attr1); // 53
so in your case that could be something like:
variableName.result.data.offers //variableName is variable that your "consoling"
Method JSON.stringify doesn't get yout specified value from JSON structure, it's converts JSON object to string.
console.dir provides a good representation of object than console.log().U can try with both
console.log(result.data.offers[0]);
console.dir(result.data.offers[0]);

Nested object JSON serialization in WebAPI

I am using .NET 4.0, MVC 4, Web API. I have following data structure:
Dictionary<Actor, Int32> TopActorToMovieCount = new Dictionary<Actor, Int32>(10);
And following entry in WebApiConfig:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
In my Controller, I am returning TopActorToMovieCount this way:
[HttpGet]
public HttpResponseMessage HighestMovies()
{
return Request.CreateResponse(HttpStatusCode.OK, MvcApplication.TopActorToMovieCount);
}
But the JSON output it is giving is:
{"api.Models.Actor":137,"api.Models.Actor":125,"api.Models.Actor":99,"api.Models.Actor":96,"api.Models.Actor":83,"api.Models.Actor":82,"api.Models.Actor":81,"api.Models.Actor":79,"....
Why it is not giving JSON structure for object of Actor?
I am sure that I am missing something, bout couldn't figure out. I tried adding following, but it didn't work:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
PS: When I switch to XML output, it works fine.
See similar question here: Not ableTo Serialize Dictionary with Complex key using Json.net
In this case, you are using "Actor" as the Key of your dictionary. Dictionary stores key/value pairs. So when creating the JSON response, it interprets the "Actor" as a key which is converted to a string, and the "Int32" as the value thus giving you
{"api.Models.Actor":137} or {key:value}
because
Actor.ToString() would result in "api.Models.Actor"
Here's a link to the definition of Dictionary: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

Getting data from JSON Array

my JSON response is as given below
JSON response is
{"code":201,"message":[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]]}.
i want to take the data correspond to 'message'.i used JSON Array.and got response as
JSON array response is
[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]].
Now how can i access each array in that?
You should expand on what you have done, what language you are using, etc. Normally, you should be able to index into the array with the standard notation. In python for example you can do something along the lines of json_data["message"][0] to access the first array and json_data["message"][1] to access the second.
something like :
var d = JSON.parse('{"code":201,"message":[["TEST Action","NA","30-11--2011"],["TEST Action 2","NA","30-11--2011"]]}')
and then you can access each array in message part as :
d.message.forEach(function(obj) { console.log(obj); });

Standardized way to serialize JSON to query string?

I'm trying to build a restful API and I'm struggling on how to serialize JSON data to a HTTP query string.
There are a number of mandatory and optional arguments that need to be passed in the request, e.g (represented as a JSON object below):
{
"-columns" : [
"name",
"column"
],
"-where" : {
"-or" : {
"customer_id" : 1,
"services" : "schedule"
}
},
"-limit" : 5,
"return" : "table"
}
I need to support a various number of different clients so I'm looking for a standardized way to convert this json object to a query string. Is there one, and how does it look?
Another alternative is to allow users to just pass along the json object in a message body, but I read that I should avoid it (HTTP GET with request body).
Any thoughts?
Edit for clarification:
Listing how some different languages encodes the given json object above:
jQuery using $.param: -columns[]=name&-columns[]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
PHP using http_build_query: -columns[0]=name&-columns[1]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
Perl using URI::query_form: -columns=name&-columns=column&-where=HASH(0x59d6eb8)&-limit=5&return=column
Perl using complex_to_query: -columns:0=name&-columns:1=column&-limit=5&-where.-or.customer_id=1&-where.-or.services=schedule&return=column
jQuery and PHP is very similar. Perl using complex_to_query is also pretty similar to them. But none look exactly the same.
URL-encode (https://en.wikipedia.org/wiki/Percent-encoding) your JSON text and put it into a single query string parameter. for example, if you want to pass {"val": 1}:
mysite.com/path?json=%7B%22val%22%3A%201%7D
Note that if your JSON gets too long then you will run into a URL length limitation problem. In which case I would use POST with a body (yes, I know, sending a POST when you want to fetch something is not "pure" and does not fit well into the REST paradigm, but neither is your domain specific JSON-based query language).
There is no single standard for JSON to query string serialization, so I made a comparison of some JSON serializers and the results are as follows:
JSON: {"_id":"5973782bdb9a930533b05cb2","isActive":true,"balance":"$1,446.35","age":32,"name":"Logan Keller","email":"logankeller#artiq.com","phone":"+1 (952) 533-2258","friends":[{"id":0,"name":"Colon Salazar"},{"id":1,"name":"French Mcneil"},{"id":2,"name":"Carol Martin"}],"favoriteFruit":"banana"}
Rison: (_id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller#artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258')
O-Rison: _id:'5973782bdb9a930533b05cb2',age:32,balance:'$1,446.35',email:'logankeller#artiq.com',favoriteFruit:banana,friends:!((id:0,name:'Colon Salazar'),(id:1,name:'French Mcneil'),(id:2,name:'Carol Martin')),isActive:!t,name:'Logan Keller',phone:'+1 (952) 533-2258'
JSURL: ~(_id~'5973782bdb9a930533b05cb2~isActive~true~balance~'!1*2c446.35~age~32~name~'Logan*20Keller~email~'logankeller*40artiq.com~phone~'*2b1*20*28952*29*20533-2258~friends~(~(id~0~name~'Colon*20Salazar)~(id~1~name~'French*20Mcneil)~(id~2~name~'Carol*20Martin))~favoriteFruit~'banana)
QS: _id=5973782bdb9a930533b05cb2&isActive=true&balance=$1,446.35&age=32&name=Logan Keller&email=logankeller#artiq.com&phone=+1 (952) 533-2258&friends[0][id]=0&friends[0][name]=Colon Salazar&friends[1][id]=1&friends[1][name]=French Mcneil&friends[2][id]=2&friends[2][name]=Carol Martin&favoriteFruit=banana
URLON: $_id=5973782bdb9a930533b05cb2&isActive:true&balance=$1,446.35&age:32&name=Logan%20Keller&email=logankeller#artiq.com&phone=+1%20(952)%20533-2258&friends#$id:0&name=Colon%20Salazar;&$id:1&name=French%20Mcneil;&$id:2&name=Carol%20Martin;;&favoriteFruit=banana
QS-JSON: isActive=true&balance=%241%2C446.35&age=32&name=Logan+Keller&email=logankeller%40artiq.com&phone=%2B1+(952)+533-2258&friends(0).id=0&friends(0).name=Colon+Salazar&friends(1).id=1&friends(1).name=French+Mcneil&friends(2).id=2&friends(2).name=Carol+Martin&favoriteFruit=banana
The shortest among them is URL Object Notation.
How about you try this sending them as follows:
http://example.com/api/wtf?
[-columns][]=name&
[-columns][]=column&
[-where][-or][customer_id]=1&
[-where][-or][services]=schedule&
[-limit]=5&
[return]=table&
I tried with a REST Client
And on the server side (Ruby with Sinatra) I checked the params, it gives me exactly what you want. :-)
Another option might be node-querystring. It also uses a similar scheme to the ones you've so far listed.
It's available in both npm and bower, which is why I have been using it.
Works well for nested objects.
Passing complex objects as query parameters of a url.
In the example below, obj is the JSON object to pass into query parameters.
Injecting JSON object as query parameters:
value = JSON.stringify(obj);
URLSearchParams to convert a string to an object representing search params. toString to retain string type for appending to url:
queryParams = new URLSearchParams(value).toString();
Pass the query parameters using template literals:
url = `https://some-url.com?key=${queryParams}`;
Now url will contain the JSON object as query parameters under key (user-defined name)
Extracing JSON from url:
This is assuming you have access to the url (either as string or URL object)
url_obj = new URL(url); (only if url is NOT a URL object, otherwise ignore this step)
Extract all query parameters in the url:
queryParams = new URLSearchParams(url_obj.search);
Use the key to extract the specific value:
obj = JSON.parse(queryParams.get('key').slice(0, -1));
slice() is used to extract a tailing = in the query params which is not required.
Here obj will be the same object passed in the query params.
I recommend to try these steps in the web console to understand better.
You can test with JSON examples here: https://json.org/example.html