[英]Newbie cant get JSON
在LiveCode中,我有一個連接到本地主機MongoDB的堆棧,該堆棧具有一個帶有mouseup處理程序的按鈕和MergJSON函數JSONToArray以及兩個字段:“ A”(接收服務器應答)和“ B”(接收服務器應答)解碼的JSON。
這是按鈕的腳本:
on mouseup
set the hideConsoleWindows to true
put shell("C:\\mongodb\bin\mongo.exe --eval" && quote & \
"printjson(db.test.findOne())" & quote) into pJSON
put pJSON into fld "a"
put JSONToArray(pJSON) into tArray
put tArray["a"] into fld "B"
end mouseup
mouseup之后,fld“ A”的內容為:
MongoDB shell version: 2.2.7
connecting to: test
{ "_id" : ObjectId("52e3f87c8da8b1efb07004c9"), "a" : 1 }
該腳本失敗,並顯示以下LiveCode錯誤:
executing at 8:58:32 PM
Type could not decode JSON: invalid token near 'MongoDB'
Object Completo
Line repeat for each line tKey in mergJSONDecode(pJSON,"tArray")
Hint could not decode JSON: invalid token near 'MongoDB'
如果我將腳本更改為:
on mouseup
put shell("C:\\mongodb\bin\mongo.exe --eval" && quote & "printjson(db.test.find())" & quote) into pJSON
put pJSON into fld "A"
end mouseup
字段“ A”得到這個:
MongoDB shell version: 2.2.7
connecting to: test
{
_"_mongo" : connection to 127.0.0.1,
_"_db" : test,
_"_collection" : test.test
_"_ns" : "test.test",
_"_query" : {
__
_},
_"_fields" : null,
_"_limit" : 0,
_"_skip" : 0,
_"_batchSize" : 0,
_"_options" : 0,
_"_cursor" : null,
_"_numReturned" : 0,
_"_special" : false,
_"help" : function () {
print("find() modifiers");
...
...
...
}
我正在縮短實際字段“ A”的內容,它包含很多文本。
你能指導我嗎? 我做錯了什么? 為什么我沒有JSON。 我使用在線服務檢查了{ "_id" : ObjectId("52e3f87c8da8b1efb07004c9"), "a" : 1 }
發現它不是有效的JSON。
嘗試僅輸入{到}之間的字符串,不要輸入前幾行。
on mouseUp
set the hideConsoleWindows to true
put shell("C:\mongodb\bin\mongo.exe --eval" && \
quote & "printjson(db.test.findOne())" & quote) into pJSON
put pJSON into fld "a"
put JSONToArray(line 3 to -1 of pJSON) into tArray // <-- this line changed
put tArray["a"] into fld "B"
end mouseUp
要回答“我做錯了什么?”這個問題 您首先需要了解在集合上調用.find()時的操作。
現在,正如該鏈接中的文檔將告訴您(位於頁面頂部),您不會從該調用返回結果 ,但是實際上您正在返回游標 。 現在,調用該外殼時可能會看到一系列文件。
但是發生這種情況的唯一原因是shell(以交互形式)充當REPL並評估您的語句以便打印輸出。 因此, 交互式外殼程序正在評估您的光標,並多次調用.next()方法。 在shell中工作時,這只是一種便利功能。
為了按計划以編程方式獲得結果,您需要使用此光標進行某種操作才能實際看到結果。 現在,您可以創建一個循環,在其中循環遍歷每次調用.next()的結果,但是出於您的目的, .toArray()方法就足夠了。
因此,以稍微擴展的方式,為獲得清晰的定義,您將具有以下腳本形式:
var cursor = db.test.find();
var results = cursor.toArray();
printjson( results );
或作為使用方法鏈的一般一種襯墊 :
printjson( db.test.find().toArray() )
這將發出您需要的文檔的JSON 數組 。
或者,您可以使用.findOne()方法,該方法將僅返回一個文檔 ,您可以將該文檔傳遞給printjson()
函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.