summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author最萌小汐 <sumneko@hotmail.com>2022-09-20 21:20:01 +0800
committer最萌小汐 <sumneko@hotmail.com>2022-09-20 21:20:01 +0800
commit25acc18ff5ec25d5cf4a052dfba11c777847f86e (patch)
treec889eae30b48027258624845accaa099d834dcb1
parentf01679bde3a0e132bd862f959d24d07d3b343aff (diff)
downloadlua-language-server-25acc18ff5ec25d5cf4a052dfba11c777847f86e.zip
improve `jsonToLua`
-rw-r--r--script/core/code-action.lua16
-rw-r--r--script/core/command/jsonToLua.lua17
2 files changed, 26 insertions, 7 deletions
diff --git a/script/core/code-action.lua b/script/core/code-action.lua
index 4eb21ff8..1e19d466 100644
--- a/script/core/code-action.lua
+++ b/script/core/code-action.lua
@@ -624,24 +624,32 @@ local function checkJsonToLua(results, uri, start, finish)
end
local startOffset = guide.positionToOffset(state, start)
local finishOffset = guide.positionToOffset(state, finish)
- local jsonStart = text:match('()[%{%[]', startOffset + 1)
+ local jsonStart = text:match('()["%{%[]', startOffset + 1)
if not jsonStart then
return
end
- local jsonFinish
+ local jsonFinish, finishChar
for i = math.min(finishOffset, #text), jsonStart + 1, -1 do
local char = text:sub(i, i)
if char == ']'
or char == '}' then
jsonFinish = i
+ finishChar = char
break
end
end
if not jsonFinish then
return
end
- if not text:sub(jsonStart, jsonFinish):find '"%s*%:' then
- return
+ if finishChar == '}' then
+ if not text:sub(jsonStart, jsonFinish):find '"%s*%:' then
+ return
+ end
+ end
+ if finishChar == ']' then
+ if not text:sub(jsonStart, jsonFinish):find ',' then
+ return
+ end
end
results[#results+1] = {
title = lang.script.ACTION_JSON_TO_LUA,
diff --git a/script/core/command/jsonToLua.lua b/script/core/command/jsonToLua.lua
index fb0fc6c9..8d9e8ba1 100644
--- a/script/core/command/jsonToLua.lua
+++ b/script/core/command/jsonToLua.lua
@@ -1,5 +1,5 @@
local files = require 'files'
-local json = require 'json'
+local json = require 'jsonc'
local util = require 'utility'
local proto = require 'proto'
local define = require 'proto.define'
@@ -17,15 +17,26 @@ return function (data)
local start = guide.positionToOffset(state, data.start)
local finish = guide.positionToOffset(state, data.finish)
local jsonStr = text:sub(start + 1, finish)
- local suc, res = pcall(json.decode, jsonStr)
- if not suc then
+ local suc, res = pcall(json.decode, jsonStr:match '[%{%[].+')
+ if not suc or res == json.null then
proto.notify('window/showMessage', {
type = define.MessageType.Warning,
message = lang.script('COMMAND_JSON_TO_LUA_FAILED', res:match '%:%d+%:(.+)'),
})
return
end
+ ---@cast res table
local luaStr = util.dump(res)
+ if jsonStr:sub(1, 1) == '"' then
+ local key = jsonStr:match '^"([^\r\n]+)"'
+ if key then
+ if key:match '^[%a_]%w*$' then
+ luaStr = ('%s = %s'):format(key, luaStr)
+ else
+ luaStr = ('[%q] = %s'):format(key, luaStr)
+ end
+ end
+ end
proto.awaitRequest('workspace/applyEdit', {
label = 'json to lua',
edit = {