Assign variable with JSON string - ruby

I have a JSON string and I want to assign it to a variable. How can I do that?
my_var = 'test text'
my_json = '{"text": "#{my_var}", "info": "great", "username": "Testuser", "avatar": "green"}'
does not work. Thanks

"#{work}" - allow interpolation
'#{not work}' - not allow
' "#{not work}" ' - not allow
" '#{work}' " - allow interpolation
Ref

Related

INSERT on Oracle with error in AdonisJS. What is the right way to do this?

When attempting to insert into Oracle using the Adonis Database, an error is generated for all fields of type string.
I am using AdonisJS 4.1 and Oracle 11.
JSON Submitted:
{
"codepi": "1",
"codoem": "5",
"datcer": "01/01/2007",
"cerapr": "2586",
"unimed": "Size",
"medepi": "P",
"desepi": "Ear Protector 01"
}
Code in Controller:
'use strict'
const Database = use ('Database')
class EstoqueEpiController {
  async store ({response, request}) {
    const data = request.only ([
      'codepi',
      'codoem',
      datcer,
      'cerapr',
      'unimed',
      'medepi',
      'desepi',
    ])
    response = await Database.connection ('oracle')
      .table ('USU_T096EPI')
      .insert ({
        USU_CodEpi: data.codepi,
        USU_CodOem: date.codoem,
        USU_DatCer: data.datcer,
        USU_CerApr: data.cerapr,
        USU_UniMed: data.unimed,
        USU_MedEpi: data.medepi,
        USU_DesEpi: data.desepi,
      })
    Database.close ()
    return response
  }
}
module.exports = EpiController
Error returned:
"message": "insert into \" USU_T096EPI \ "(\" USU_CerApr \ ", \" USU_CodEpi \ ", \" USU_CodOem \ ", \" USU_DatCer \ ", \" USU_DesEpi \ ", \" USU_MedEpi \ ", \ "USU_UniMed \") values ​​(: 1,: 2,: 3,: 4,: 5,: 6,: 7) - ORA-00904: \ "USU_UniMed \": invalid identifier "
ORA-00904 oracle documentation :
You tried to execute a SQL statement that included an invalid column name or the column name is missing. This commonly occurs when you reference an invalid alias in a SELECT statement.
Check the column names
&
I don't know if it has an impact (line 4) :
const data = request.only ([
'codepi',
'codoem',
datcer, < 'datcer'
'cerapr',
'unimed',
'medepi',
'desepi',
])

How to convert JSON-string to Binary using a Record? Web.Contents + POST + Power Query

Web.Contents method takes Content as Binary
I use this code. It works
query = "{
""field1"" : ""value1"",
""field2"" : ""value2"",
""field3"" : {
""sub_field_3_1"" : [""value_3_1_1"", ""value_3_1_2"", ""value_3_1_1""],
""sub_field_3_2"" : [""value_3_2_1"", ""value_3_2_2"", ""value_3_2_1""]
}
}",
content = Text.ToBinary(query),
Web.Contents("https://my_url", [
Headers = [#"Content-Type"="text/xml; charset=utf-8"],
Content=content
])
I understand, it is not a good workaround, because there is no reason to make double-conversions. But I could not find a way how to apply a Record, and it should look like this:
record = [
field1 = value1,
field2 = value2,
field3 = [
sub_field_3_1 = {value_3_1_1, value_3_1_2, value_3_1_1},
sub_field_3_2 = {value_3_2_1, value_3_2_2, value_3_2_1}
]
],
content = SOME_CONVERTER(record),
Web.Contents("https://my_url", [
Headers = [#"Content-Type"="text/xml; charset=utf-8"],
Content = content
])
Tried to use Uri.BuildQueryString (How to POST a multipart/form-data using Power Query's Web.Contents) but it does not form Binary properly
record = [
field1 = value1,
field2 = value2,
field3 = [
sub_field_3_1 = {value_3_1_1, value_3_1_2, value_3_1_1},
sub_field_3_2 = {value_3_2_1, value_3_2_2, value_3_2_1}
]
],
content = Text.ToBinary(Uri.BuildQueryString(record)),
Web.Contents("https://my_url", [
Headers = [#"Content-Type"="text/xml; charset=utf-8"],
Content=content
]
Is there some better workaround?
For now, your hard-coded JSON string is one of the better solutions.
It's less than ideal, but you could roll your own value-to-JSON transforming function like toJson:
let
record = [
field1 = "value1",
field2 = "value2",
field3 = [
sub_field_3_1 = {"value_3_1_1", null, 3.2},
sub_field_3_2 = {"value_3_2_1", "value_3_2_2", "value_3_2_1"}
]
],
toJson = (v as any) as text =>
if v is null then "null" else
if v is logical or v is number then Text.From(v) else
if v is text then """" & Text.Replace(Text.Replace(v, "\", "\\"), """", "\""") & """" else
if v is list then "[" & Text.Combine(List.Transform(v, #toJson), ", ") & "]" else
if v is record then "{" &
Text.Combine(List.Transform(
Record.FieldNames(v),
(n) => #toJson(n) & ": " & #toJson(Record.Field(v, n))), ", ")
& "}" else
error "not implemented",
jsonText = toJson(record)
in
jsonText
Some deficiencies compared to what a real Json.FromValue library function should do:
only primitive text escaping
see json.org for all the special characters you'd need to escape
doesn't handle cyclic M values, special not-numbers, or other types of value types
will choke on very large values (string concat will use a lot of memeory)
SOME_CONVERTER == Json.FromValue
let
record = [
field1 = "value1",
field2 = "value2",
field3 = [
sub_field_3_1 = {"value_3_1_1", "value_3_1_2", "value_3_1_1"},
sub_field_3_2 = {"value_3_2_1", "value_3_2_2", "value_3_2_1"}
]
],
content = Json.FromValue(record),
web=Web.Contents("https://my_url", [
Headers = [#"Content-Type"="text/xml; charset=utf-8"],
Content = content
])
in
web

Splitting a single string of hashes into an array of hashes

I can't get regex to split the string to give the desired result.
http://rubular.com/r/ytFwP3ivAv - according to rubular this expression should work.
str = "{"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}, {"DATE"=>"11/26/2013 11:10", "DESC"=>"Hold-up alarm", "LOCATION"=>"4725 S KIRKMAN RD", "DISTRICT"=>"E5", "INCIDENT"=>"2013-00496235"}"
sub_str_array = str.split(/({"[\w"=>\/ :,()-]*})/)
# the desired result - each hash is an element in an array
puts the_split[0] #=> {"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}
Is there another way (an easier way) to convert these string hashes into an array of hashes?
You can use this:
require 'json'
yourstr = '[' + '{"DATE"=>"11/26/2013 11:15", "DESC"=>"Accident (minor)", "LOCATION"=>"12 S THORNTON AV", "DISTRICT"=>"C5", "INCIDENT"=>"2013-00496193"}, {"DATE"=>"11/26/2013 11:10", "DESC"=>"Hold-up alarm", "LOCATION"=>"4725 S KIRKMAN RD", "DISTRICT"=>"E5", "INCIDENT"=>"2013-00496235"}, {"DATE"=>"11/26/2013 11:08", "DESC"=>"Missing person - adult", "LOCATION"=>"4818 S SEMORAN BV 503", "DISTRICT"=>"K1", "INCIDENT"=>"2013-00496198"}, {"DATE"=>"11/26/2013 11:07", "DESC"=>"911 hang up", "LOCATION"=>"311 W PRINCETON ST", "DISTRICT"=>"C2", "INCIDENT"=>"2013-00496231"}' + ']'
my_hash = JSON.parse(yourstr.gsub("=>", ":"))
puts my_hash[0]
You've set str as an object. Wrap it in quotes and it should work.
It may be better to use %Q(string goes here) rather than double quotes.
You can use eval "[#{str}]", if str is hardcoded and nobody can change it.

trouble assigning value to nested hash

I have a nested hash I want to assign a value to, but ruby keeps complaining about it.
the hash:
data = {
name: contact.xpath('./span[1]').text.delete("\r\n").strip,
email: contact.xpath('./a').text,
offices: [
postal: contact.text.split("\r\n")[4].strip,
tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s
],
url: url
}
my assignment
data[:offices][:postal] = ""
error:
Line 42 - data[:offices][:postal] = "" -- in `[]='
#<TypeError: can't convert Symbol into Integer>
I've tried a handful of other syntaxes, but to no avail. Any help is appreciated :)
offices: [
postal: contact.text.split("\r\n")[4].strip,
tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s
],
That is not a nested hash. Use curly braces:
offices: {
postal: contact.text.split("\r\n")[4].strip,
tel: /(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})/.match(contact).to_s
},

Web Mail client helper not translating newlines in body of msg (mvc3/asp.net)?

Can somebody tell me why newlines are not being translated in the email message when passed in as the body of the web mail helper?
string body = "First line here" + Environment.NewLine + Environment.NewLine +
"Here is a newline...";
WebMail.Send(
"myemail#mycom.com",
"Subject",
body, "myemail#mycom.com");
Output is all on the same line in the email message itself. Thx!
Default value for parameter isBodyHtml from send method is true that's why Environment.NewLine is ignored. If you'll set isBodyHtml = false it will work.
WebMail.Send(to: "mail#gmail.com", subject: "Test", isBodyHtml:false, body: "First line here" + Environment.NewLine + "Second line.");

Resources