Backslashes and other character combinations in logic apps json - json

I was wondering why logic apps connectors process json and then adds different characters like "\" "\r\n" and more, in json string when it goes through the workflow.
Is it possible to somehow dodge this problem in logic apps? how do i handle a problem like this best practice.
I have managed to create a Azure Function app that i use to remove these kind of characters and combination through a process of .Replace(). bu i feel like this could be done in a much better way.
Any ideas or suggestions would be much appreciated!
Example:
{
"Employee": "{\"Address\":\"507 - 20th Ave. E.\\r\\nApt. 2A\",\"BirthDate\":\"1948-12-08T00:00:00Z\",\"City\":\"Seattle\",\"Country\":\"USA\",\"EmployeeID\":\"1\",\"Extension\":\"5467\",\"Firstname\":\"Nancy\",\"HireDate\":\"1992-05-01T00:00:00Z\",\"HomePhone\":\"(206) 555-9857\",\"Lastname\":\"Davolio\",\"Notes\":\"Education includes a BA in psychology from Colorado State University in 1970. She also completed \\\"The Art of the Cold Call.\\\" Nancy is a member of Toastmasters International.\",\"PhotoPath\":\"http://accweb/emmployees/davolio.bmp\",\"PostalCode\":\"98122\",\"Region\":\"WA\",\"ReportsTo\":\"2\",\"Title\":\"Sales Representative\",\"TitleOfCourtesy\":\"Ms.\"}"
}

It depends on the expected type of the connector input. For example, HTTP Body or Azure DocumentDB expect type of "object". For those there are no escape characters added and JSON is serialized as-is. However some connectors have a field which is a string like Email Body. In that case the designer takes the input from designer and stringifies it (escaping characters) so a valid string is sent.
Which connector are you referencing here?

Related

Parse Json in Logic App from Stream Analytics -> Service Hub -> Logic Apps

I'm trying to build a logic app that inserts data into a Sql database. The data is coming from s Stream Analytics job, outputting it on a Service Bus topic, consumed in Logic Apps in Service Bus trigger.
To populate the properties of the row inserted (lets say it only has one column 'Name'), I've found that this should work using following syntax:
"body": {
"Name": "#{json(decodeBase64(triggerBody()['ContentData'])).Name}"
},
Provided the message body contains a 'Name' property.
However I get following error message when running this:
{"code":"InvalidTemplate","message":"Unable to process template language expressions in action 'Insert_row' inputs at line '1' and column '2017': 'The template language function 'json' parameter is not valid. The provided value '#\u0006string\b3http://schemas.microsoft.com/2003/10/Serialization/��{\"time\":\"2016-05-25T10:29:17.4953250Z\",\"Name\":\"Y-Axis\",\"Value\":81.0,\"Date\":\"2016-05-25T10:29:17.4953250\",\"EventProcessedUtcTime\":\"2016-05-25T10:29:17.5525449Z\",\"PartitionId\":2,\"EventEnqueuedUtcTime\":\"2016-05-25T10:29:17.2220000Z\"}\u0001' cannot be parsed: 'Unexpected character encountered while parsing value: #. Path '', line 0, position 0.'. Please see https://aka.ms/logicexpressions#json for usage details.'."}
So it seems like that the content is enclosed in another envelope that is preventing json parsing to work.
1) Any simple way how to get around this?
2) Isn't such an integration all within Microsoft Stack just supposed to work without this mocking around?
Thanks,
Stefan
with the limited string functions available in he workflow definition language I had to use a long winded way for removing the additional strings
#{json(substring(replace(decodeBase64(triggerBody()['ContentData']),'#string3http://schemas.microsoft.com/2003/10/Serialization/��', ''),0,sub(length(replace(decodeBase64(triggerBody()['ContentData']),'#string3http://schemas.microsoft.com/2003/10/Serialization/��', '')),1))).fieldname}
is there a better way to do this
Thanks for reporting this, you're right it should simply work. There is a known issue where ASA ServiceBus output JSON is being wrapped in a XML header. It will be addressed in a near future but can't specify a particular date. Could you please workaround it (maybe using substring/replace) until then ?
cheers,
Chetan
Sorry for the delay in getting back, this issue is now fixed. Its exposed under a new compatibility level (1.1) to avoid breaking existing solutions. Please use this URL to configure your job with compat level 1.1 and give it a try.
cheers!

Clojure name binding to REST JSON data

I'm a Frontend Engineer, our team is switching many of our old services to micro services written in clojure. The main issue I'm seeing is that clojure naming conventions prefer hyphens to-separate-words in variable names. This means if you straight map variables into JSON any JS consumer would need to access this data using bracket notation e.g. response['to-separate-words']. This is obviously not ideal. I thought this would be a easy best practice to lookup but I've been looking for an hour and it seems like all the docs I read avoid this issue but using single words. Has anyone else dealt with this.
You might use camel-snake-kebab library which supports most of the combinations. You can plug it in into most of the JSON libraries for Clojure (cheshire, cli-json, data.json - as mentioned by Elogent) as they usually have an option to provide a function for handling property name mangling.
For example with cheshire:
Generate JSON with camel case property names:
(cheshire.core/generate-string {:my-clojure-key "abc"}
{:key-fn camel-snake-kebab.core/->camelCaseString})
Result:
{"myClojureKey":"abc"}
Parse JSON to get map with kebab case keys:
(cheshire.core/parse-string "{\"myClojureKey\":\"abc\"}"
camel-snake-kebab.core/->kebab-case-keyword)
Result:
{:my-clojure-key "abc"}
There is also an example for data.json in camel-snake-kebab readme.

JSON REST endpoint returning / consuming JSON literals

Is it advisable or not in a RESTful web service to use JSON literal values (string / number) as input parameter in the payload or in the response body?
If I have an endpoint PUT /mytodolist is it OK for it to accept a JSON string literal value "Take out the rubbish" in the request payload (with Content-Type=application/json) or should it accept a JSON object instead ({"value":"Take out the rubbish"})?
Similarly, is it fine for GET /mytodolist/1 to return "Take out the rubbish" in the response body or should it return a proper JSON object {"value":"Take out the rubbish"}
Spring MVC to makes implementing and testing such endpoints easy, however clients have flagged this as non standard or hard to implement. In my point of view JSON literals are JSON, but not JSON objects, so I'd say it is fine. I have found no recommendations using Google.
EDIT 1: Clafirication
The question is entirely about the 'standard', if it allows this or not.
I understand the problem with the extensibility, but one can never design a fully extensible interface IMHO. If changes need to be done, we can try extending what we have in a backwards compatible way, but there will come a time when it becomes messy and an other approach is required - which is commonly handled by versioning the API in one way or another. I find it a fair point even though, because using literals as request/response body immediately becomes inextensible, while coming up with a reasonable one-attribute JSON object does not.
It is also understood that some frameworks have problems with handling JSON literals, this is the origin of this question. The tool I used happened to support this, so I thought this was all right, but the front-end library did not.
Still, what I am intending to find out right now, is if using JSON literals is according to the de-facto standard (even if it is a cornercase) or not.
I would recommend to use JSON object always. One reason is that for Content-Type application/json people expect something staring with "{" and not all frameworks will handle json literals properly. Second reason is that probably you will add some additional attributes to you list item (due date, category, priority, etc). And then you'll break backward compatibility, by adding new field.
It may be acceptable in the context of your example, but keep in mind that unambiguous interfaces are easier to use and that will encourage adoption.
For example, your interface could interpret "Take out he rubbish" as the same as {task:"take out the rubbish"}, but once you add additional properties (eg "when" or "who") the meaning of a solitary string in the request becomes ambiguous. It's inevitable that you'll add support for new properties as your interface matures.

Is it possible to parse a Google+ (Google Plus) profile page?

If you view the source of a Google+ profile page, it appears rather complex. It seems most of the data is kept in a huge JSON-like objects. However, they don't seem to be really JSON, since they don't get recognized when I try to decode them. I am hoping the format is more clear to other people here. How would you go about parsing it? It seems it would fairly trivial, if you know where to start.
Here is a sample profile, for example: http://plus.google.com/104560124403688998123
Here's a PHP API I'm working on. It can download and parse the data for a profile page and people's public relationships.
https://github.com/jmstriegel/php.googleplusapi
The JSON piece is a bit mangled. To generate valid JSON, you basically have to remove the first 5 characters that prevent XSRF attacks and then add in all the nulls that have been removed. Here's the code specific to handling parsing the weird Google Plus JSON responses:
https://github.com/jmstriegel/php.googleplusapi/blob/master/lib/GooglePlus/GoogleUtil.php
Call GoogleUtil::FetchGoogleJSON( $url ) and you'll get back a giant array that you can then pull data from. Using this, it should be trivial to make a proxy service to translate stuff into valid json(p) for you to use in your own apps.
I don't have access to Google+ yet, so I'll just answer the general question - that is, how to parse JSON.
JSON is just JavaScript, so parsing it is as simple as evaluating the script. To do this, use the eval() JavaScript function.
var obj = eval('{"JSON":"goes here"}');
Another option is to leverage a console tool. Popular modern browsers pretty much all have them. I recommend Firebug for Firefox in particular.
Using Firefox, log into Google+, then open the Firebug console. You can use the console's dir() command to create a browseable representation of the data. Ex:
console.dir(eval('{"JSON":"goes here"}'));
Sorry I can't be more specific about how to get a handle on Google+'s JSON in particular; without access to the service, this is about the best I can do blind. Good luck!
Thanks to Jason for the excellent php class which reads a profile page into an array.
I've used this class as a base and then parsed it, based upon Russell Beattie's python code from the original appspot rss feed application.
Code here
A few notes:
I use this to merge G+ and WP feeds, hence writing posts into an intermediate array ($items).
I have a convention of creating a pseudo title in Google Plus posts, by emboldening a line and adding two newlines before writing the post. The function getTitle strips this out as a better formatted title in my website and getSummary produces the rest of the post with duplicating the title.
It's made up of a number of parts, an object describing your picasa images, one describing the fields on your profile, one describing your friends.
Most of the long numbers are the internal IDs of people, posts and photos. For instance, my ID is 105249724614922381234. Other than that, it could be parsed if you needed to.

What is JSON and what is it used for?

I've looked on Wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it.
I have been building applications using PHP, MySQL and JavaScript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON Structure
Here is an example of JSON data:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
JSON in JavaScript
JSON (in Javascript) is a string!
People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in its own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.
See Javascript object Vs JSON
When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
Example on how to use the JSON parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.
References
JSON.org
Wikipedia
Json in 3 minutes (Thanks mson)
Using JSON with Yahoo! Web Services (Thanks gljivar)
JSON to CSV Converter
Alternative JSON to CSV Converter
JSON Lint (JSON validator)
The Concept Explained - No Code or Technical Jargon
What is JSON? – How I explained it to my wifeTM
Me: “It’s basically a way of communicating with someone in writing....but with very specific rules.
Wife: yeah....?
Me: In prosaic English, the rules are pretty loose: just like with cage fighting. Not so with JSON. There are many ways of describing something:
• Example 1: Our family has 4 people: You, me and 2 kids.
• Example 2: Our family: you, me, kid1 and kid2.
• Example 3: Family: [ you, me, kid1, kid2]
• Example 4: we got 4 people in our family: mum, dad, kid1 and kid2.
Wife: Why don’t they just use plain English instead?
Me: They would, but remember we’re dealing with computers. A computer is stupid and is not going to be able to understand sentences. So we gotta be really specific when computers are involved otherwise they get confused. Furthermore, JSON is a fairly efficient way of communicating, so most of the irrelevant stuff is cut out, which is pretty hand. If you wanted to communicate our family, to a computer, one way you could do so is like this:
{
"Family": ["Me", "Wife", "Kid1", "Kid2"]
}
……and that is basically JSON. But remember, you MUST obey the JSON grammar rules. If you break those rules, then a computer simply will not understand (i.e. parse) what you are writing.
Wife: So how do I write in Json?
A good way would be to use a json serialiser - which is a library which does the heavy lifting for you.
Summary
JSON is basically a way of communicating data to someone, with very, very specific rules. Using Key Value Pairs and Arrays. This is the concept explained, at this point it is worth reading the specific rules above.
In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:
var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
var MyObject = {
'StringProperty' : 'Value',
'IntProperty' : 12,
'ArrayProperty' : [ 1, 2, 3],
'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
}; // MyObject is now an object with property values set.
You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.
You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
A useful link for detail is here:
http://secretgeek.net/json_3mins.asp
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML.
I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
Update (ten years later): Don't do this, use JSON.parse
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
What is JSON?
JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript.
JSON values can consist of:
objects (collections of name-value pairs)
arrays (ordered lists of values)
strings (in double quotes)
numbers
true, false, or null
JSON is language independent.
JSON with PHP?
After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.
Json_encode - returns the JSON representation of values
Json_decode - Decodes the JSON String
Json_last_error - Returns the last error occured.
JSON Syntax and Rules?
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
Sometimes technicality is given where none is required, and while many of the top voted answers are accurately technical and specific, I personally don't think they are any more easy to understand, or succinct, as what can be found on Wikipedia, or in official documentation.
The way I like to think of JSON is exactly what it is - a language within a world of different languages. However, the difference between JSON and other languages is that "everyone" "speaks" JSON, along with their "native language."
Using a real world example, let's pretend we have three people. One person speaks Igbo as their native tongue. The second person would like to interact with the first person, however, the first person speaks Yoruba as their first language.
What can we do?
Thankfully, the third person in our example grew up speaking English, but also happens to speak both Igbo and Yoruba as second languages, and so can act as an intermediary between the first two individuals.
In the programming world, the first "person" is Python, the second "person" is Ruby, and the third "person" is JSON, who just so happens to be able to "translate" Ruby into Python and vice versa! Now obviously this analogy isn't a perfect one, but, as someone who is bilingual, I believe it's an easy way to look at how JSON interacts with other programming languages.
We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.
For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON).
That is one problem where you could use JSON perhaps.
Here is something practical: Yahoo JSON
The difference between JSON and conventional syntax would be as follows (in Javascript)
Conventional
function Employee(name, Id, Phone, email){
this.name = name;
this.Id = Id;
this.Phone = Phone;
this.email = email;
}
//access or call it as
var Emp = new Employee("mike","123","9373849784","mike.Anderson#office.com");
With JSON
if we use JSON we can define in different way as
function Employee(args){
this.name = args.name;
this.Id = args.Id;
this.Phone = args.Phone;
this.email = args.email;
}
//now access this as...
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.
so this line below is the way of doing things with JSON(just a simple way to define things)
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
It's very simple. JSON stands for Java Script Object Notation. Think of it as an alternative to using XML for transferring data between software components.
For example, I recently wrote a bunch of web services that returned JSON, and some Javascript developers then wrote code which called the services and consumed the information returned in that format.
JSON(Javascript object notation) is a light weight data format for data exchange/transfer. Its in key value pair as the JavaScript is.
For REST API its widely used for data transfer from server to client. Nowadays many of the social media sites are using this. Although I don't see this as robust as XML with respect of data types. XML has very rich datatypes and XSD. JSON is bit lacking in this.
For same amount of string data JSON will be lighter compare to XML as XML has all that opening and closing tags, etc...
In the Java context, one reason why JSON might want to be used, is that it provides a very good alternative to Java's Serialization framework, which has been shown (historically) to be subject to some fairly serious vulnerabilities.
Joshua Bloch discusses this in depth in Item 85 "Prefer Alternatives to Java Serialization" (Effective Java 3rd Edition)
Java's Serialization was initially meant to translate data structures into a format that could be easily transmitted or stored. JSON meets this requirement, without the serious exploits referred to above.
Try the following code to parse your php json response:
read.php
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajax({
url:'index.php',
data:{},
type:"POST",
success:function(result) {
jsondecoded = $.parseJSON(result);
$.each(jsondecoded, function(index, value) {
$("#servers").text($("#servers").text() + " " + value.servername);
console.log(value.start);
console.log(value.end);
console.log(value.id);
});
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
</script>
server.php
<?php
echo '[{"start":"2017-08-29","end":"2017-09-01","id":"22"},{"start":"2017-09-03","end":"2017-09-06","id":"23"}]';
?>