1

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.

3
  • When you say "a JSON object", you start with the object instance or with the JSON string? Commented Oct 18, 2018 at 19:24
  • @ConnorsFan JSON object / instance Commented Oct 18, 2018 at 19:26
  • I think I probably need something more like $filter=username eq 'john' and password eq '1234'. Commented Oct 18, 2018 at 19:30

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good idea, although I think my question should probably be worded differently because I am querying for these values, so I need the $filter operator and a different syntax.
I modified the answer and the stackblitz according to your comments. Please edit the question if that is the format that you need.
0

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+'');

2 Comments

JSON.parse converts a string into an object, the opposite of what I need.
Thank you for trying, but JSON.stringify will not format the string for OData querying.
0

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.