delegate.replace() is not working on Array List Grails 2.3.8 - html

Here's my code in order to replace HTML tags:
def str
String.metaClass.removeHtml {
def removeThisHtml = [
[htmlCode: "`", value: "`"],
[htmlCode: "#", value: "#"],
[htmlCode: "&", value: "&"],
[htmlCode: "\", value: "\\"],
[htmlCode: """, value: '"'],
[htmlCode: "'", value: "'"],
[htmlCode: "<", value: "<"],
[htmlCode: ">", value: ">"]
]
removeThisHtml.each { element ->
str = delegate.replace(element.htmlCode, element.value)
}
return str
}
And here is the code form my controller:
def getProjectLists() {
def currentUser = springSecurityService.currentUser
def kups = ([['name':'<b>Sample 1</b>'.removeHtml()],['name':'<b>Sample 2</b>']])
render kups as JSON
}
My expected output is:
< b >Sample1< / b> Sample2
But the output is:
Sample1 Sample2

I think what you really want is to escape HTML - display HTML tags and entities, so the function's name removeHtml is a bit misleading, escapeHtml would fit it better.
Generally I recommend not to do things like this by your self as others have already done that and most likely do it better.
For example Apache Commons has an StringEscapeUtils.escapeHtml method.
String.metaClass.removeHtml {
return org.apache.commons.lang.StringEscapeUtils.escapeHtml(delegate)
}

Related

Seeding rails project with Json file

I'm at a lost and my searches have gotten me nowhere.
In my seeds.rb file I have the following code
require 'json'
jsonfile = File.open 'db/search_result2.json'
jsondata = JSON.load jsonfile
#jsondata = JSON.parse(jsonfile)
jsondata[].each do |data|
Jobpost.create!(post: data['title'],
link: data['link'],
image: data['pagemap']['cse_image']['src'] )
end
Snippet of the json file looks like this:
{
"kind": "customsearch#result",
"title": "Careers Open Positions - Databricks",
"link": "https://databricks.com/company/careers/open-positions",
"pagemap": {
"cse_image": [
{
"src": "https://databricks.com/wp-content/uploads/2020/08/careeers-new-og-image-sept20.jpg"
}
]
}
},
Fixed jsondata[].each to jasondata.each. Now I'm getting the following error:
TypeError: no implicit conversion of String into Integer
jsondata[] says to call the [] method with no arguments on the object in the jsondata variable. Normally [] would take an index like jsondata[0] to get the first element or a start and length like jsondata[0, 5] to get the first five elements.
You want to call the each method on jsondata, so jsondata.each.
So this is very specific to what you have posted:
require 'json'
file = File.open('path_to_file.json').read
json_data = JSON.parse file
p json_data['kind'] #=> "customsearch#result"
# etc for all the other keys
now maybe the json you posted is just the first element in an array:
[
{}, // where each {} is the json you posted
{},
{},
// etc
]
in which case you will indeed have to iterate:
require 'json'
file = File.open('path_to_file.json').read
json_data = JSON.parse file
json_data.each do |data|
p data['kind'] #=> "customsearch#result"
end

Why can't a select values not in double quotes from a json file in python programming

import json
f = open(r'C:\Users\Arun\Documents\Input.json',)
data = json.load(f)
json.dumps(data, separators=(",", ":"))
for i in data["notificationChannels"]:
if i["enabled"] == "true":
print(i)
But I can get the values if I use if i["type"] == "BEAN": , Why can't I pull values which are not in double quotes
Sample Json File Content:
{
"notificationChannels": [
{
"type": "BEAN",
"enabled": true,
I believe that the "json" library was build to read the value of true (without double quotes) as boolean True, so that the comparison to string "true" is wrong in the first place.
My suggestion to try:
...
if i["enabled"] == True:
...

Emit Python embedded object as native JSON in YAML document

I'm importing webservice tests from Excel and serialising them as YAML.
But taking advantage of YAML being a superset of JSON I'd like the request part of the test to be valid JSON, i.e. to have delimeters, quotes and commas.
This will allow us to cut and paste requests between the automated test suite and manual test tools (e.g. Postman.)
So here's how I'd like a test to look (simplified):
- properties:
METHOD: GET
TYPE: ADDRESS
Request URL: /addresses
testCaseId: TC2
request:
{
"unitTypeCode": "",
"unitNumber": "15",
"levelTypeCode": "L",
"roadNumber1": "810",
"roadName": "HAY",
"roadTypeCode": "ST",
"localityName": "PERTH",
"postcode": "6000",
"stateTerritoryCode": "WA"
}
In Python, my request object has a dict attribute called fields which is the part of the object to be serialised as JSON. This is what I tried:
import yaml
def request_presenter(dumper, request):
json_string = json.dumps(request.fields, indent=8)
return dumper.represent_str(json_string)
yaml.add_representer(Request, request_presenter)
test = Test(...including embedded request object)
serialised_test = yaml.dump(test)
I'm getting:
- properties:
METHOD: GET
TYPE: ADDRESS
Request URL: /addresses
testCaseId: TC2
request: "{
\"unitTypeCode\": \"\",\n
\"unitNumber\": \"15\",\n
\"levelTypeCode": \"L\",\n
\"roadNumber1\": \"810\",\n
\"roadName\": \"HAY\",\n
\"roadTypeCode\": \"ST\",\n
\"localityName\": \"PERTH\",\n
\"postcode\": \"6000\",\n
\"stateTerritoryCode\": \"WA\"\n
}"
...only worse because it's all on one line and has white space all over the place.
I tried using the | style for literal multi-line strings which helps with the line breaks and escaped quotes (it's more involved but this answer was helpful.) However, escaped or multiline, the result is still a string that will need to be parsed separately.
How can I stop PyYaml analysing the JSON block as a string and make it just accept a block of text as part of the emitted YAML? I'm guessing it's something to do with overriding the emitter but I could use some help. If possible I'd like to avoid post-processing the serialised test to achieve this.
Ok, so this was the solution I came up with. Generate the YAML with a placemarker ahead of time. The placemarker marks the place where the JSON should be inserted, and also defines the root-level indentation of the JSON block.
import os
import itertools
import json
def insert_json_in_yaml(pre_insert_yaml, key, obj_to_serialise):
marker = '%s: null' % key
marker_line = line_of_first_occurrence(pre_insert_yaml, marker)
marker_indent = string_indent(marker_line)
serialised = json.dumps(obj_to_serialise, indent=marker_indent + 4)
key_with_json = '%s: %s' % (key, serialised)
serialised_with_json = pre_insert_yaml.replace(marker, key_with_json)
return serialised_with_json
def line_of_first_occurrence(basestring, substring):
"""
return line number of first occurrence of substring
"""
lineno = lineno_of_first_occurrence(basestring, substring)
return basestring.split(os.linesep)[lineno]
def string_indent(s):
"""
return indentation of a string (no of spaces before a nonspace)
"""
spaces = ''.join(itertools.takewhile(lambda c: c == ' ', s))
return len(spaces)
def lineno_of_first_occurrence(basestring, substring):
"""
return line number of first occurrence of substring
"""
return basestring[:basestring.index(substring)].count(os.linesep)
embedded_object = {
"unitTypeCode": "",
"unitNumber": "15",
"levelTypeCode": "L",
"roadNumber1": "810",
"roadName": "HAY",
"roadTypeCode": "ST",
"localityName": "PERTH",
"postcode": "6000",
"stateTerritoryCode": "WA"
}
yaml_string = """
---
- properties:
METHOD: GET
TYPE: ADDRESS
Request URL: /addresses
testCaseId: TC2
request: null
after_request: another value
"""
>>> print(insert_json_in_yaml(yaml_string, 'request', embedded_object))
- properties:
METHOD: GET
TYPE: ADDRESS
Request URL: /addresses
testCaseId: TC2
request: {
"unitTypeCode": "",
"unitNumber": "15",
"levelTypeCode": "L",
"roadNumber1": "810",
"roadName": "HAY",
"roadTypeCode": "ST",
"localityName": "PERTH",
"postcode": "6000",
"stateTerritoryCode": "WA"
}
after_request: another value

Getting an attribute from json

I am trying to get a specific attribute from a json object. This is my code.
require 'json'
def print_f(json)
json.map do |person|
puts "\n#{person['name'] }, \n #{person['lastname']}"
end.join
end
a = '{"JSON": {"name": "Fernando", "lastname": "Soto"}}'
obj = JSON.parse(a)['JSON']
text = ''
text += print_f(obj)
puts text
When I do:
puts obj.inspect
it returns:
"`{"name"=>"Fernando", "lastname"=>"Soto"}"
But when I try to run it, it throws an error:
Traceback (most recent call last):
5: from t.rb:14:in `<main>'
4: from t.rb:4:in `print_f'
3: from t.rb:4:in `map'
2: from t.rb:4:in `each'
1: from t.rb:5:in `block in print_f'
t.rb:5:in `[]': no implicit conversion of String into Integer (TypeError)
Hope you can help me.
Since you're only accessing a single record, map is not relevant:
def print_f(json)
puts "\n#{person['name'] }, \n #{person['lastname']}"
end
If you did want to iterate over them then you'd need to change your document to this:
a = '{"JSON": [ {"name": "Fernando", "lastname": "Soto"}} ]'
That's an array of objects (Hashes) so map then applies.
Another thing I've noticed is if you're intending to return a string puts is the wrong way to do it. Instead you want:
def print_f(json)
"\n#{person['name'] }, \n #{person['lastname']}"
end
This is because puts always returns nil regardless of input.
well this is how it works, just in case someone else needs this specific example, hope you find this example useful. Special thanks to tadman.
require 'json'
def print_f(json)
json
json.map do |person|
"\n#{person['name'] },\n #{person['lastname']}\n#{person['name2'] },\n #{person['lastname2']}"
end.join
end
a = '{"key1": [{"name": "Fernando", "lastname": "Soto" ,"name2": "Luis", "lastname2": "Bautista"}]}'
obj = JSON.parse(a)['key1']
text = ''
text += print_f(obj)
print text
And this is the result.
Fernando,
Soto
Luis,
Bautista

Look for JSON example with all allowed combinations of structure in max depth 2 or 3

I've wrote a program which process JSON objects. Now I want to verify if I've missed something.
Is there an JSON-example of all allowed JSON structure combinations? Something like this:
{
"key1" : "value",
"key2" : 1,
"key3" : {"key1" : "value"},
"key4" : [
[
"string1",
"string2"
],
[
1,
2
],
...
],
"key5" : true,
"key6" : false,
"key7" : null,
...
}
As you can see at http://json.org/ on the right hand side the grammar of JSON isn't quite difficult, but I've got several exceptions because I've forgotten to handles some structure combinations which are possible. E.g. inside an array there can be "string, number, object, array, true, false, null" but my program couldn't handle arrays inside an array until I ran into an exception. So everything was fine until I got this valid JSON object with arrays inside an array.
I want to test my program with a JSON object (which I'm looking for). After this test I want to be feel certain that my program handle every possible valid JSON structure on earth without an exception.
I don't need nesting in depth 5 or so. I only need something in nested depth 2 or max 3. With all base types which nested all allowed base types, inside this base type.
Have you thought of escaped characters and objects within an object?
{
"key1" : {
"key1" : "value",
"key2" : [
"String1",
"String2"
],
},
"key2" : "\"This is a quote\"",
"key3" : "This contains an escaped slash: \\",
"key4" : "This contains accent charachters: \u00eb \u00ef",
}
Note: \u00eb and \u00ef are resp. charachters ë and ï
Choose a programming language that support json.
Try to load your json, on fail the exception's message is descriptive.
Example:
Python:
import json, sys;
json.loads(open(sys.argv[1]).read())
Generate:
import random, json, os, string
def json_null(depth = 0):
return None
def json_int(depth = 0):
return random.randint(-999, 999)
def json_float(depth = 0):
return random.uniform(-999, 999)
def json_string(depth = 0):
return ''.join(random.sample(string.printable, random.randrange(10, 40)))
def json_bool(depth = 0):
return random.randint(0, 1) == 1
def json_list(depth):
lst = []
if depth:
for i in range(random.randrange(8)):
lst.append(gen_json(random.randrange(depth)))
return lst
def json_object(depth):
obj = {}
if depth:
for i in range(random.randrange(8)):
obj[json_string()] = gen_json(random.randrange(depth))
return obj
def gen_json(depth = 8):
if depth:
return random.choice([json_list, json_object])(depth)
else:
return random.choice([json_null, json_int, json_float, json_string, json_bool])(depth)
print(json.dumps(gen_json(), indent = 2))