Convert a String to JSON in scala.html file - json

I am currently using a list of PropertyDTO s in my scala.html file to populate a view with Play2. The propertyDTO has a String attribute "value" which contains a JSON String. I want to convert this string to a JSON object in the scala.html file, and iterate through the JSON object collection. When trying the following,
val json = Json.parse(property.value),as[JsObject] within the scala code, it prints the expression. I would wish to know if my approach is correct, and if not , is there a suitable solution.
Code --> scala.html
#(propertyList : List[PropertyDTO])
#for(property <- propertyList){
#if(property.isInputProperty){
#if(property.propertyType=="BL"){
val json = Json.parse(property.value).as[JsObject]
}
}
}

I would not advise doing this in a template - the point of having templates, and not embedding HTML generation directly into your Scala code, is to separate the view logic from the application logic. If you go embedding Scala code like this in your template, then what's the point in using a template?
Best practice is to prepare all your data for rendering before calling the template, and then pass it into the template, and keep the template as dumb as possible, just iterating and rendering values.

The problem is that you need to declare code to be interpreted as scala code by putting an # in front of it. The line
val json = Json.parse(property.value).as[JsObject]
gets interpreted as HTML as there is no # sign in the line indicating scala code. What you can do is declare a whole block to contain scala code using #{ ... }.
For example you can store the result of your for comprehension in a variable for later use in the template:
#import play.api.libs.json._
#validPropertiesAsJson = #{
for{
property <- propertyList
if property.isInputProperty
if property.propertyType == "BL"
} yield Json.parse(property.value).as[JsObject]
}
And later in the template use #validPropertiesAsJson to include the value.
More information can be found in the playframework documentation: http://www.playframework.com/documentation/2.2.0/ScalaTemplates
Keep in mind to put as little logic into the template as possible.

Related

how to parse dynamic json object in Typescript

I have a json object in my typescript which is returned from server side. One of the keys is dynamic. How do I parse and extract the value for that key.
Ex: serverResponse.detailsLMN.allList
Ex :serverResponse.detailsLMN.deleteList
In the above , 'LMN' is dynamic.
It can be serverResponse.detailsLMN.allList or serverResponse.detailsPQR.allList.
Assuming,
const temp = 'LMN' or 'PQR', how can I use temp to parse JSON object here.
Like : serverResponse.details{temp}.allList
Not sure if I understood your question correctly. But try doing
let data = JSON.parse(serverResponse);
((JSON.stringify(serverResponse)).includes("LMN")) ? serverResponse.detailsLMN.allList
: serverResponse.detailsPQR.allList
^The above code is the same as the if statement. If you don't know the ES6 ternary conditional statement then here's a link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
To parse, simply use JSON.parse(). To extract the value, since I can't see the format of the output, it's better to console.log(serverResponse) the whole response and then walk through the Object in Chrome console to see how to get to your specific value.

Return empty array when transforming xml data to json

I am returning some xml structure as json using the built-in MarkLogic json module. For the most part it does what I expect. However, when an element marked as an array is empty, it returns an empty string instead of an empty array. Here is an example:
xquery version "1.0-ml";
import module namespace json = "http://marklogic.com/xdmp/json"
at "/MarkLogic/json/json.xqy";
let $config := json:config("custom")
return (
map:put( $config, "array-element-names", ("item") ),
json:transform-to-json(<result>
<item>21</item>
<item>22</item>
<item>23</item>
</result>, $config),
json:transform-to-json(<result></result>, $config))
Result:
{"result":{"item":["21", "22", "23"]}}
{"result":""}
I would expect an empty array if there were no items matching in the array-element-name called "item". i.e.
{"result":{"item":[]}}
Is there some way to configure it so it knows the element is required ?
No - it will not create anything that is not there. In your case, what if the XML was more complex. There is no context of 'where' such an element might live - so it could not create it even if it wanted to.
Solution is to repair the content if needed by adding one element - or transforming it into the json-basic namespace - where those elements live inside of of an element noted as an array (which can be empty) - or third, use an XSD to hint to the processor what to do . But that would still need a containing element for the 'array' - and then the items would be minOccurance=0. But if this is the case, then repair and transform into the json/basic namespace is probably nice and simple for your example.

Parsing large JSON file with Scala and JSON4S

I'm working with Scala in IntelliJ IDEA 15 and trying to parse a large twitter record json file and count the total number of hashtags. I am very new to Scala and the idea of functional programming. Each line in the json file is a json object (representing a tweet). Each line in the file starts like so:
{"in_reply_to_status_id":null,"text":"To my followers sorry..
{"in_reply_to_status_id":null,"text":"#victory","in_reply_to_screen_name"..
{"in_reply_to_status_id":null,"text":"I'm so full I can't move"..
I am most interested in a property called "entities" which contains a property called "hastags" with a list of hashtags. Here is an example:
"entities":{"hashtags":[{"text":"thewayiseeit","indices":[0,13]}],"user_mentions":[],"urls":[]},
I've browsed the various scala frameworks for parsing json and have decided to use json4s. I have the following code in my Scala script.
import org.json4s.native.JsonMethods._
var json: String = ""
for (line <- io.Source.fromFile("twitter38.json").getLines) json += line
val data = parse(json)
My logic here is that I am trying to read each line from twitter38.json into a string and then parse the entire string with parse(). The parse function is throwing an error claiming:
"Type mismatch, expected: Nothing, found:String."
I have seen examples that use parse() on strings that hold json objects such as
val jsontest =
"""{
|"name" : "bob",
|"age" : "50",
|"gender" : "male"
|}
""".stripMargin
val data = parse(jsontest)
but I have received the same error. I am coming from an object oriented programming background, is there something fundamentally wrong with the way I am approaching this problem?
You have most likely incorrectly imported dependencies to your Intellij project or modules into your file. Make sure you have the following lines imported:
import org.json4s.native.JsonMethods._
Even if you correctly import this module, parse(String: json) will not work for you, because you have incorrectly formed a json. Your json String will look like this:
"""{"in_reply_...":"someValue1"}{"in_reply_...":"someValues2"}"""
but should look as follows to be a valid json that can be parsed:
"""{{"in_reply_...":"someValue1"},{"in_reply_...":"someValues2"}}"""
i.e. you need starting and ending brackets for the json, and a comma between each line of tweets. Please read the json4s documenation for more information.
Although being almost 6 years old, I think this question deserves another try.
JSON format has a few misunderstandings in people's minds, especially how they are stored and how they are read back.
JSON documents, are stored as either a single object having all the other fields, or an array of multiple object possibly in same format. this second part is important because arrays in almost every programming language are defined by angle brackets and values separated by commas (note here I used a person object as my single value):
[
{"name":"John","surname":"Doe"},
{"name":"Jane","surname":"Doe"}
]
also note that everything except brackets, numbers and booleans are enclosed in quotes when written into file.
however, there is another use that is not official but preferred to transfer datasets easily where every object, or document as in nosql/mongo language, are stored in a new line like this:
{"name":"John","surname":"Doe"}
{"name":"Jane","surname":"Doe"}
so for the question, OP has a document written in this second form, but tries an algorithm written to read the first form. following code has few simple changes to achieve this, and the user must read the file knowing that:
var json: String = "["
for (line <- io.Source.fromFile("twitter38.json").getLines) json += line + ","
json=json.splitAt(json.length()-1)._1
json+= "]"
val data = parse(json)
PS: although #sbrannon, has the correct idea, the example he/she gave has mistakenly curly braces instead of angle brackets to surround the data.
EDIT: I have added json=json.splitAt(json.length()-1)._1 because the code above ends with a trailing comma which will cause parse error per the JSON format definition.

VBA getting values from a collection?

I am very new to VBA and I can not figure out how to get values from a Collection.
This is my code:
Dim p As Object
Set p = JSON.parse(Response.Content)
Dim links As Object
Set links = p.Item("links")
In the debugger for "links" I see:
I am using this library to parse json : http://www.ediy.co.nz/vbjson-json-parser-library-in-vb6-xidc55680.html
The part I have in json is:
"links":[
{
"rel":"next",
"href":"www.google.com"
}
]
How can I get the value of "rel" here?
Don't forget the bang operator, designed for collection access by key:
links(1)!rel
or:
links(1)![rel] 'When there are spaces or reserved words.
I will answer my own question:
links(1).Item("rel")
worked...
Regards..
Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.
JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.
Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.
You can see the full VBA code here

Write json object with controller using rendered jsp

I use Spring MVC.
I want to render some jsp by forwarding to it. And then I want to write the result to json.
For exmple I want to render my complex jsp and on exit I want to get:
{"result":"ok","html":"......."}
How can I do this?
I've tried to look at
request.getRequestDispatcher("tutorMini").forward(request, response)
But if I can't pass response to it, bcz it should write all output to it.
And I've tried to use some json tags in jsp, but it has some troubles with hierarchy:
HTML output with jsp:include and json-taglib
Since you need to apply additional conversion when inserting HTML into JSON (escape ' and "), you cannot write output of your JSP to the response directly.
So, you need to create an instance of ServletResponseWrapper that would save the output (by overriding getWriter() and/or getOutputStream()) and pass it to RequestDispatcher.include() (it looks more appropriate than forward() for this case):
MyServletResponseWrapper wrapper = new MyServletResponseWrapper(response);
request.getRequestDispatcher("tutorMini").include(request, wrapper);
String html = wrapper.getSavedOutput();
Then you can insert the saved content into JSON, escaping it appropriately.