Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to parse string to integer #1664

Closed
austince opened this issue May 9, 2023 · 5 comments
Closed

Ability to parse string to integer #1664

austince opened this issue May 9, 2023 · 5 comments

Comments

@austince
Copy link

austince commented May 9, 2023

Please describe your feature request.

Sometimes there are integers encoded as strings (because, sigh) and it would be nice to be able to parse them dynamically for things like sorting.

Describe the solution you'd like
If we have data1.yml like:
(please keep to around 10 lines )

- version: "10"
- version: "9"
- version: "11"

And we run a command:

yq 'sort_by(.version | parseint)'

it could output

- version: "9"
- version: "10"
- version: "11"

Describe alternatives you've considered

I tried adding a 0 to try to force integer evaluation to no avail.

Additional context
Generally being able to change the data type of a field while processing would be useful. Is this already available in some way I haven't found?

@austince
Copy link
Author

austince commented May 9, 2023

Ah, found something along these lines is possible with tag manipulation and map_values.

map_values(. | .version type = "!!int")

A proper parseint func still might be clearer and handle errors better? Unsure.

@mikefarah
Copy link
Owner

parse_int and other scalars make sense I think, I'd take a PR for this.

In the meantime, you can actually use the yaml decode operator which will automatically detect the type:

yq '"3" | @yamld' -n
3
yq '"3" | @yamld | tag' -n
!!int

@venkatesh2090
Copy link

Hi, is this a duplicate of #71 as well?

@mikefarah
Copy link
Owner

Yep 👍🏼 This is fixed in the 4.40 pre-release here: https://github.com/mikefarah/yq/releases/tag/v4.40.1 - will be looking to make an official 4.41 release soon

@mikefarah
Copy link
Owner

Fixed in 4.40.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants