mpen
mpen

Reputation: 282915

How to read a value from a JSON file?

I've never written a line of Lua before. How can I read a value from a JSON file?

The JSON looks like this:

{"debug":false,"server":"dev3"}

I need to access the "server" value from a Lua script.

In PHP I'd write

$server = json_decode(file_get_contents('config.json'), true)['server']

What's the equivalent Lua?

Upvotes: 1

Views: 4541

Answers (2)

Rochet2
Rochet2

Reputation: 1156

Lua does not have a function to do this by default. You could take a look at some libraries that offer json parsing capabilities: http://lua-users.org/wiki/JsonModules

Otherwise you could maybe use some regex to parse the values or some small program that reads the json format

Upvotes: 4

Nicol Bolas
Nicol Bolas

Reputation: 473547

There isn't one.

Lua is an embedded scripting language. Most facilities are provided by the application it is embedded within. As such, Lua itself has only the bare minimum facilities in its standard libraries (which applications can even remove or modify as they see fit).

So Lua does not have built-in facilities for doing things like JSON parsing. Now, you can write a Lua script to parse JSON. Or you can find a JSON parser written for Lua. And if you're using Lua in some kind of web-app server backend, I'd wager that the system provides one. But Lua doesn't have anything for that out-of-the-box.

Upvotes: 4

Related Questions