www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Iterate JSON during compile-time.

reply Tariq Siddiqui <m.tariqsiddiqui gmail.com> writes:
Hello everyone,

I want to iterate over the JSON using CTFE. I have tried both 
std.json and vibe.data.json, but there is no luck. I am not sure 
what I am missing.
```d
import std.stdio;
import std.json;
import std.array;
import vibe.data.json;

void main()
{
	enum string config = `{ "ModelNames": [ "Bank", "Biller", 
"Aggregator" ] }`;
	const auto c1 = parseJSON(config);
	immutable auto c2 = parseJsonString(config);
	
	foreach (key; c1["ModelNames"].array)
		writeln(key.get!string);

	foreach (key; c2["ModelNames"])
		writeln(key.get!string);

	// static foreach (key; c1["ModelNames"].array)
	// 	pragma(msg, key.get!string);

	// static foreach (key; c2["ModelNames"])
	// 	pragma(msg, key.get!string);
}
```
Apr 10
parent Tariq Siddiqui <m.tariqsiddiqui gmail.com> writes:
On Saturday, 10 April 2021 at 14:03:55 UTC, Tariq Siddiqui wrote:
 Hello everyone,

 I want to iterate over the JSON using CTFE. I have tried both 
 std.json and vibe.data.json, but there is no luck. I am not 
 sure what I am missing.
 ```d
 import std.stdio;
 import std.json;
 import std.array;
 import vibe.data.json;

 void main()
 {
 	enum string config = `{ "ModelNames": [ "Bank", "Biller", 
 "Aggregator" ] }`;
 	const auto c1 = parseJSON(config);
 	immutable auto c2 = parseJsonString(config);
 	
 	foreach (key; c1["ModelNames"].array)
 		writeln(key.get!string);

 	foreach (key; c2["ModelNames"])
 		writeln(key.get!string);

 	// static foreach (key; c1["ModelNames"].array)
 	// 	pragma(msg, key.get!string);

 	// static foreach (key; c2["ModelNames"])
 	// 	pragma(msg, key.get!string);
 }
 ```
Thanks to Vladimir, the problem is solved by his advice. ```d import std.algorithm.iteration; import std.stdio; import std.json; import std.array; import vibe.data.json; void main() { enum string config = `{ "ModelNames": [ "Bank", "Biller", "Aggregator" ] }`; immutable auto c1 = parseJSON(config); immutable auto c2 = parseJsonString(config); static foreach (key; c1["ModelNames"].array.map!(item => item).array) pragma(msg, key.get!string); static foreach (key; c2["ModelNames"].array.map!(item => item).array) pragma(msg, key.get!string); } ```
Apr 10