Hello,
(I am a noob from python)
I want to check if one string is in a list of strings, but the list of strings comes from a json file, how do I do that?
Here are my desperate attempts to figure it out.
import json
#[test.json
["Alice", "Bob", "Eve"]
]#
var json_thingy=parseFile("test.json")
echo type(json_thingy)
var normal_thingy=["Alice","Bob","Eve"]
echo type(normal_thingy)
echo "Alice" in normal_thingy #true
# echo "Alice" in json_thingy
#Error: unhandled exception: /opt/homebrew/Cellar/nim/1.6.14/nim/lib/pure/json.nim(565, 9) `node.kind == JObject` [AssertionDefect]
# json_thingy.as(seq[string])
#Hallucinated by ChatGTP
echo json_thingy.getElems() #@["Alice", "Bob", "Eve"]
echo type(json_thingy.getElems) #seq[JsonNode]
#echo "Alice" in json_thingy.getElems() #type mismatch: got <seq[JsonNode], string>
Thanks.
I think I figured it out:
echo "Alice" in to(json_thingy,seq[string])
But if there is a better way please tell me.
The way you did it there is indeed the most elegant solution. Other JSON libraries do it with very similar syntax. For funsies I added another 2 ways that you can do that in the way you were initially attempting: By fetching elems from your JsonNode that contained the arrays and transforming that to a seq[string]. That does exactly the same as the to proc, it just means you write the code for the transformation yourself. It might also give you a bit of insight into how you can transform sequences/arrays in nim in the future when it's not just JSON ;-)
import std/[json, sequtils, sugar]
let jsonFile = parseFile("./test.json")
# Normal JSON parsing the most elegant solution
let strings1 = jsonFile.to(seq[string])
echo "Alice" in strings1
# Normally
var strings2: seq[string] = @[]
for node in jsonFile.getElems():
strings2.add(node.getStr())
echo "Alice" in strings2
# With sequtils "mapIt" which functions like JS "map" and is the functional equivalent to python list comprehensions.
# but you just need to provide an expression that implicitly has the varibale "it" provided.
# "it" is the iterable aka the varibale containing each entry in your seq as you loop over it.
let strings3 = jsonFile.getElems().mapIt(it.getStr())
echo "Alice" in strings3