Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing float value from string by jq

I have a particular JSON data which contain float value that I need to conditionally process over an array of JSON. This is an example of one JSON instance:

[
   {
      "a": "0",
      "b": "66.67",
      "c": "0",
      "d": "0"
   },
   {
      "a": "12.33",
      "b": "0",
      "c": "60.2",
      "d": "19.3"
   },
   {
      "a": "70.0",
      "b": "92.67",
      "c": "0",
      "d": "0"
   }
]

and I wish to conditionally select like

cat mydata.json | jq '.[] | select((.a > 50) and (.b > 50))'

and it should sound like

{
      "a": "70.0",
      "b": "92.67",
      "c": "0",
      "d": "0"
}

The problem is my original data is a string value and I have no idea how to parse it for a conditional selection.

like image 512
Sakares Avatar asked Jan 03 '18 12:01

Sakares


People also ask

How to convert string value to float in jQuery?

Find code to convert String to float or double using jQuery. To convert, use JavaScript parseFloat() function parses a string and returns a floating point number. var sVal = '234.54'; var iNum = parseFloat(sVal); //Output will be 234.54.

What does parse float do?

The parseFloat() function is used to accept a string and convert it into a floating-point number. If the input string does not contain a numeral value or If the first character of the string is not a number then it returns NaN i.e, not a number.

What does parseFloat return?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.


1 Answers

Simply with jq's tonumber function:

jq '.[] | select((.a|tonumber) > 50 and (.b|tonumber) > 50)' mydata.json

The output:

{
  "a": "70.0",
  "b": "92.67",
  "c": "0",
  "d": "0"
}
like image 68
RomanPerekhrest Avatar answered Oct 01 '22 07:10

RomanPerekhrest