How to convert to String? - octave

Below commands :
theta = zeros(2, 1);
printf(theta)
Give error : error: printf: format TEMPLATE must be a string
Is there function to convert the theta to a String or to print the theta value ?
Reading the octave doc : http://www.network-theory.co.uk/docs/octave3/octave_140.html this does seem possible ?

If you are trying to sprint to the stdout stream then you can use printf without converting to a string as it will do this for you but it works like any string formatting function in any language where the first argument is a string followed by variables you want to format and insert into that string. for your simple case:
printf('%f', theta)
If you are just trying to print to the console however, I would suggest rather using sprintf or display. Matlab doesn't have a printf command and I would always advocate keeping your Octave code directly portable to Matlab when possible.

matstr function
For my case : printf(mat2str(theta , 2))
src : https://www.gnu.org/software/octave/doc/interpreter/Converting-Numerical-Data-to-Strings.html

Use num2str()
eg
str_theta = num2str(theta)
Octave documentaion on converting numbers to strings

Related

Jmeter - JSON Extractor - Large numbers erroring

Hope someone can help me :)
I have the response json below :
"endValue":{"amount":12515920.97,"currencyCode":"EUR"}
and I'm using the JSON extractor to retrieve the "amount" number and is working fine for any numbers that have up till 6 characters before the decimal point, but for large numbers like this one, is actually saving "1.251592097E7" on my variable. Is this a limitation or is there any other way that I can have the full number extracted?
Thanks in advance!
If you want to store the value "as is" the easiest option is going for the JSR223 Post-Processor and fetch your value using Groovy
Example code:
vars.put('your_variable_name_here', new groovy.json.JsonSlurper().parse(prev.getResponseData()).endValue.amount as String)
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
All the digits of the number are there, it is just that it is being displayed in scientific notation.
You can format the number when the program needs to display it, for example using DecimalFormat:
import java.text.DecimalFormat;
public class Example{
public static void main(String []args){
double x = 12515920.97;
DecimalFormat df = new DecimalFormat("#,###,###,##0.00");
String result = df.format(x);
System.out.println(result);
}
}
Outputs:
12,515,920.97

How to get slice of string in OCaml?

So I'm writing a JSON parser in OCaml, and I need to get a slice of a string. More specifically, I need to get the first n characters of a string so I can pattern-match with them.
Here's an example string:
"null, \"field2\": 25}"
So, how could I use just a couple lines of OCaml code to get just the first 4 characters (the null)?
P.S. I've already thought about using something like input.[0..4] but I'm not entirely sure how that works, I'm reasonably new to OCaml and the ML family.
Using build-in sub function should do the work:
let example_string = "null, \"field2\": 25}"
(*val example_string : string = "null, \"field2\": 25}" *)
let first_4 = String.sub example_string 0 4
(*val first_4 : string = "null" *)
I suggest you to look at official documentation:
https://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html
And if you are not doing this for self teaching I would strongly suggest using one of available libraries for the purpose, such as yojson (https://ocaml-community.github.io/yojson/yojson/Yojson/index.html) for example.

Ambiguous format output in nodejs

I am having output in following format as
"[{"a":"a1"},{"a":"a2"}]"
I want to actually extract it in array of json:
[
{
"a":"a1"
},
{
"a":"a2"
}
]
How to convert it?
You have tagged this with Node-RED - so my answer assumes that is the environment you are working in.
If you are passing a message to the Debug node and that is what you see in the Debug sidebar, that indicates your msg.payload is a String with the contents of [{"a":"a1"},{"a":"a2"}] - the Debug sidebar doesn't escape quotes when displaying strings like that.
So you likely already have exactly what you want - it just depends what you want to do with it next.
If you want to access the contents you need to parse it to a JavaScript Object. You can do this by passing your message through a JSON node.
Assuming your input contains the double quotes in the beginning and end, it is not possible to directly JSON.parse() the string.
In your case, you need to remove the first and last character (the double quotes) from your string before parsing it.
const unformattedString = '"[{"a":"a1"},{"a":"a2"}]"'
const formattedString = unformattedString.substr(1, unformattedString.length - 2)
const json = JSON.parse(formattedString)
The variable json now contains your JSON object.
I would suggest a different method which will get your work done without using any third party library.
var a = '[{"a":"a1"},{"a":"a2"}]';
var b = JSON.parse(a);
console.log(b); // b will return [{"a":"a1"},{"a":"a2"}]
Another way which is eval function which is generally not recommended
var d = eval(a);
If you want to use JQuery instead use :
var c = $.parseJSON(a);

Importing JSON into R with in-line quotation marks

I'm attempting to read the following JSON file ("my_file.json") into R, which contains the following:
[{"id":"484","comment":"They call me "Bruce""}]
using the jsonlite package (0.9.12), the following fails:
library(jsonlite)
fromJSON(readLines('~/my_file.json'))
receiving an error:
"Error in parseJSON(txt) : lexical error: invalid char in json text.
84","comment":"They call me "Bruce""}]
(right here) ------^"
Here is the output from R escaping of the file:
readLines('~/my_file.json')
"[{\"id\":\"484\",\"comment\":\"They call me \"Bruce\"\"}]"
Removing the quotes around "Bruce" solves the problem, as in:
my_file.json
[{"id":"484","comment":"They call me Bruce"}]
But what is the issue with the escapement?
In R strings literals can be defined using single or double quotes.
e.g.
s1 <- 'hello'
s2 <- "world"
Of course, if you want to include double quotes inside a string literal defined using double quotes you need to escape (using backslash) the inner quotes, otherwise the R code parser won't be able to detect the end of the string correctly (the same holds for single quote).
e.g.
s1 <- "Hello, my name is \"John\""
If you print (using cat¹) this string on the console, or you write this string on a file you will get the actual "face" of the string, not the R literal representation, that is :
> cat("Hello, my name is \"John\"")
Hello, my name is "John"
The json parser, reads the actual "face" of the string, so, in your case json reads :
[{"id":"484","comment":"They call me "Bruce""}]
not (the R literal representation) :
"[{\"id\":\"484\",\"comment\":\"They call me \"Bruce\"\"}]"
That being said, also the json parser needs double-quotes escaping when you have quotes inside strings.
Hence, your string should be modified in this way :
[{"id":"484","comment":"They call me \"Bruce\""}]
If you simply modify your file by adding the backslashes you will be perfectly able to read the json.
Note that the corresponding R literal representation of that string would be :
"[{\"id\":\"484\",\"comment\":\"They call me \\\"Bruce\\\"\"}]"
in fact, this works :
> fromJSON("[{\"id\":\"484\",\"comment\":\"They call me \\\"Bruce\\\"\"}]")
id comment
1 484 They call me "Bruce"
¹
the default R print function (invoked also when you simply press ENTER on a value) returns the corresponding R string literal. If you want to print the actual string, you need to use print(quote=F,stringToPrint), or cat function.
EDIT (on #EngrStudent comment on the possibility to automatize quotes escaping) :
Json parser cannot do quotes escaping automatically.
I mean, try to put yourself in the computer's shoes and image you should parse this (unescaped) string as json: { "foo1" : " : "foo2" : "foo3" }
I see at least three possible escaping giving a valid json:
{ "foo1" : " : \"foo2\" : \"foo3" }
{ "foo1\" : " : "foo2\" : \"foo3" }
{ "foo1\" : \" : \"foo2" : "foo3" }
As you can see from this small example, escaping is really necessary to avoid ambiguities.
Maybe, if the string you want to escape has a really particular structure where you can recognize (without uncertainty) the double-quotes needing to be escaped, you can create your own automatic escaping procedure, but you need to start from scratch, because there's nothing built-in.

Node.js eval var json parse

I'm trying to make a small parser which receives the json string and the path to get:
var args = process.argv;
var jsonToBeParsed = args[2];
var path = args[3];
var result = JSON.parse(jsonToBeParsed);
console.log(result);
console.log(result.path);
I'm calling this with
node parser.js '{"asd":"123", "qwe":"312"}' 'asd'
It gives me undefined
I think it has to be done with some eval function but I don't have too much experience with node/JS.
How can I resolve this?, I need to get the result from the command line.
Edit: I'm expecting "123" in the second log. Thanks #Esailija, the question wasn't too clear ...
I think you are trying to use dynamic property, you cannot use .path, because that literally means .path property.
Try this:
console.log(result);
console.log(result[path]);
if path === "asd", then it will work, which is statically equivalent to result["asd"] or result.asd
To add to #Esailija's answer:
node parser.js '{"path": "123"}' 'asd'
Would return 123. The dot notation expects the property name. If you have a dynamic property name, you need to use the square brackets notation.
console.log(result['ads']);
// But what you want is:
console.log(result[path]); // 'path' is a variable with the correct string
I wanted to embed the json parser into a git alias, To get a json node in bash (using node)
node -e "console.log(JSON.parse(process.argv[1]).foo.bar)" '{"foo":{"bar":"Hello World"}}'