JSON to OData String for Query - json

How can I turn a JSON object, i.e. { username: "john", password: "1234" } into an OData string query in a function using typescript? I could not find a library to do this for me (Angular 6). Here is my attempt:
function ConvertToODataString (json: Object) {
let ret_str: string = "";
for (let key in json) {
ret_str += (key + "=" + json[key] + "&");
}
if (ret_str) {
ret_str = ret_str.substr(0, ret_str.length - 1); // remove last &
}
return ret_str;
}
Does anyone know of a better way? For now, my json is not multi-leveled.

You can use for ... in to enumerate the object properties, adding each key/value pair to an array, and combine the values with Array.join:
function convertObjectToQuery(obj: Object): string {
let values = new Array<string>();
for (let prop in obj) {
values.push(`${prop} eq '${obj[prop]}'`);
}
return encodeURI("$filter=" + values.join(" and "));
}
See this stackblitz for a demo.

JSON.parse function.
Example:
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
json={ "name":"John", "age":30, "city":"New York"};
var obj = JSON.parse(json+'');

I decided to use the HttpParms module instead:
import { HttpParams } from "#angular/common/http";
const params = new HttpParams()
.set("$filter", "Username eq '" + parameters["Username"] + "' and Password eq '" + parameters["Password"] + "'")
.set("$count", "true");
console.log(params.toString());

Related

Wrong string format when i use persian and english together in Node Js

I have a node js project with MySql database. I have to use Persian data in my DB like:
UserModel = {id: 1200, firstName: 'صابر', lastName: 'سجادی' , nationalCode:'4640147800', displayName: 'saber-sajadi', status: 1, createDateTime: null };
so for run stored procedure i need to convert object to string with this Code:
let objectToString = (object) => {
let _string = "";
let i = 1;
for (let key in object) {
var val = object[key];
_string += (val == undefined || val == null) ? `null` : `'` + val + `' `;
if (i < Object.keys(object).length) {
_string += " , ";
i++;
}
}
return _string;
}
I expect the output of the function to be as follows:
but it return:
1200,'صابر','سجادی','4640147800','saber-sajadi','1',''
Please help me to solve this problem
we can use this function to solve problem:
function wrap(str){ return '\u202B' + str + '\u202C'; }

get a json property type with Newtonsoft Json

I parsed a Json string with JObject.Parse(json) and I'm trying to traverse the properties. I find that the only way to access the json type is thru it's parent node, like this:
string json = #"{
CPU: 'Intel',
Drives: [ 'DVD read/writer', '500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
foreach (var p in o.Properties())
{
Console.WriteLine("name:" + p.Name + ", value: " + p.Value);
Console.WriteLine("o[p.Name].Type: " + o[p.Name].Type); // correctly returns js type
Console.WriteLine("p.Type: " + p.Type); // returns Property for every item
Console.WriteLine("p.GetType(): " + p.GetType()); // returns Newtonsoft.Json.Linq.JProperty for every item
Console.WriteLine();
}
I suppose there must be some way to get the json type from the property. (live fiddle here)
The Value of a JProperty is a JToken. You can use the Type property on a JToken to get its JSON type. So you just need to use p.Value.Type to get what you are looking for.
Example fiddle: https://dotnetfiddle.net/CtuGGz
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = #"
{
""CPU"": ""Intel"",
""Integrated Graphics"": true,
""USB Ports"": 6,
""OS Version"": 7.1,
""Drives"": [
""DVD read/writer"",
""500 gigabyte hard drive""
]
}";
JObject o = JObject.Parse(json);
foreach (var p in o.Properties())
{
Console.WriteLine("name: " + p.Name);
Console.WriteLine("type: " + p.Value.Type);
Console.WriteLine("value: " + p.Value);
Console.WriteLine();
}
}
}

How to properly create an array of JSON objects in Typescript?

I'm trying to create an array of JSON objects in typescript. And following is the approach I have used.
var queryMutations:any = _.uniq(_.map(mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
var item = {facet: "MUTATION", term: mutation.gene + " " + mutation.proteinChange}
return item;
}
else {
return {};
}
}));
var jsonString = JSON.stringify(queryMutations);
is this the correct way to do it? Appreciate your suggestions.
To me it looks ok. I'd personally make a few layout style modifications and use backtick placeholder strings.
var queryMutations:any =
_.uniq(
_.map(
mutationData.result,
function(mutation:Mutation) {
if (mutation && mutation.gene) {
return {facet: "MUTATION",
term: `${mutation.gene} ${mutation.proteinChange}`
} else {
return {};
}
}
)
);
var jsonString = JSON.stringify(queryMutations);

How to convert jCard into first-class JSON?

I need a stable and secure convertion algorithm (any language), that can produce the final output as "first class" JSON objects. Example:
jCard format: [["version", {}, "text", "4.0"],["fn", {}, "text", "Forrest Gump"]]
First-class JSON format: {"version":"4.0","fn":"Forrest Gump"}.
In python
first, I create one function named jcard_to_json that takes a jCard as input and converts it to a "first-class" JSON object. The function iterates over the items in the jCard, and for each item, it adds a key-value pair to the json_obj dictionary, where the key is the first item in the jCard thing and the value is the fourth item
Example:-
def jcard_to_json(jcard):
json_obj = {}
for item in jcard:
json_obj[item[0]] = item[3]
return json_obj
jcard = [["version", {}, "text", "4.0"], ["fn", {}, "text", "Forrest
Gump"]]
json_obj = jcard_to_json(jcard)
In Java.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JCardTest {
public static void main(String[] args) throws JSONException {
String jcardStr = "[\"vcard\","
+ " ["
+ " [\"version\", {}, \"float\", \"4.0\"],"
+ " [\"fn\", {}, \"text\", \"John Doe\"],"
+ " [\"gender\", {}, \"text\", \"M\"],"
+ " [\"categories\", {}, \"text\", \"computers\", \"cameras\"],"
+ " [\"number\", {}, \"integer\", 12345],"
+ " [\"adr\","
+ " { \"type\": \"work\" },"
+ " \"text\","
+ " ["
+ " \"\","
+ " \"Suite D2-630\","
+ " \"2875 Laurier\","
+ " \"Quebec\","
+ " \"QC\","
+ " \"G1V 2M2\","
+ " \"Canada\""
+ " ]"
+ " ]"
+ " ]"
+ " ]";
JSONArray jcard = new JSONArray(jcardStr);
jcard = jcard.getJSONArray(1);
JSONObject result = new JSONObject();
for (int i = 0; i < jcard.length(); i++) {
JSONArray arr = jcard.getJSONArray(i);
String name = arr.getString(0);
String dataType = arr.getString(2);
if (arr.length() == 4) {
switch (dataType) {
case "integer": {
long val = arr.getLong(3);
result.put(name, val);
}
break;
case "float": {
double val = arr.getDouble(3);
result.put(name, val);
}
break;
default:
Object val = arr.get(3);
if (val instanceof JSONArray) {
result.put(name, (JSONArray) val);
} else {
result.put(name, val.toString());
}
break;
}
} else {
JSONArray resArr = new JSONArray();
for (int j = 3; j < arr.length(); j++) {
resArr.put(arr.get(j).toString());
}
result.put(name, resArr);
}
}
System.out.println(result);
}
}
This ignores the 'parameter" part (arr.get(1)) of the jCard entries.
the code is verbose to not to hide important details. it could be written more compact.
Example is based on examples in the jCard RFC7095.

how to get a key value from Json object in node js

I want to get the id value from the following json object
answerTag:
[ '[{"id":64,"name":"Coronary Artery Disease"}]',
'[{"id":64,"name":"Coronary Artery Disease"}]' ],
risk: '1' }
I had the same issue. I found that I had to remove the leading and trailing brackets before calling JSON.parse for it to work. The JSON.parse inside a try-catch didn't fail but just the same I couldn't access the values in the resultant object.
Here's the excerpt. "rows[0]" is the the first row of my MySQL result array
result = JSON.stringify(rows[0])
result = result.replace(/(^\[)/, '');
result = result.replace(/(\]$)/, '');
try {
var resultObj = JSON.parse(result);
} catch (e) {
console.log("Error, not a valid JSON string");
}
var my_value = resultObj["my_key"];
Hope this helps!
You dont have a valid JSON
as a valid json should have a key-value pair
var answerTag=
{
"key1":{"id":64,"name":"Coronary Artery Disease"},
"key2":{"id":64,"name":"Coronary Artery Disease"},
"key3":{risk: '1' }
}
So if u want to traverse that ,put it in for loop like this
getKeyValueFromJSON(answerTag);
function getKeyValueFromJSON(
for(var key in obj) {
alert("Key: " + key + " value: " + obj[key]);
}
}
Or if i am able to get it
The formed JSON is like this
var obj={
answerTag: [
'[{"id":64,"name":"Coronary Artery Disease"}]',
'[{"id":64,"name":"Coronary Artery Disease"}]' ],
risk: '1'
}
So You can use it like this
for(var key in obj) {
for(var innerKey in obj[key]) {
console.log("Key: " + innerKey + " value: " + obj[key][innerKey]);
}
}