有人能帮助我在包含一个或多个代码的文本中获取第一个json代码吗?
我试图使用以下代码:{(^'+)},但这会使代码中的所有jsons
我希望在json中获得第一段代码的所有文件都有一个或多个代码块,而我只需要获得第一个代码,即在单词"Item Definition“之后的代码。
还有两个词组的文本:
ItemDefinition
{ // I'm trying to get the code from here
"itemid": 590532217,
"shortname": "ammo.nailgun.nails",
"displayName": {
"token": "ammo.nailgun.nails",
"english": "Nailgun Nails"
},
"displayDescription": {
"token": "ammo.nailgun.nails.desc",
"english": "Standard nailgun ammunition"
},
"iconSprite": {
"instanceID": 148798
},
"category": 8,
"selectionPanel": 0,
"maxDraggable": 0,
"itemType": 1,
"amountType": 0,
"occupySlots": 0,
"stackable": 64,
"quickDespawn": false,
"rarity": 0,
"spawnAsBlueprint": false,
"inventorySelectSound": {
"instanceID": 115050
},
"inventoryGrabSound": {
"instanceID": 115050
},
"inventoryDropSound": {
"instanceID": 81228
},
"physImpactSoundDef": {
"instanceID": 60196
},
"condition": {
"enabled": false,
"max": 0.0,
"repairable": false,
"maintainMaxCondition": false,
"foundCondition": {
"fractionMin": 1.0,
"fractionMax": 1.0
}
},
"hidden": false,
"flags": 0,
"steamItem": {
"instanceID": 0
},
"Parent": {
"instanceID": 0
},
"worldModelPrefab": {
"guid": "d8c823436ceda0f42a4da54a972807bf"
},
"Traits": 8,
"panel": {
"instanceID": 0
}
} // Until here
ItemModProjectile
{
...other json code
}发布于 2021-02-17 20:50:37
尽管您可以使用regex解析JSON,但是它不可靠,在角的情况下也会失败。
您可以使用这个函数提取第一个JSON块,并解析它:
function parseFirstJson(text) {
try {
const regex = /^[^\{]*([\s\S]*?[\r\n]\})[\s\S]*$/;
let obj = JSON.parse(text.replace(regex, '$1'));
return obj;
} catch(e) {
// return JSON parse error
let obj = { error: e.toString() };
return obj;
}
}
const text =`ItemDefinition
{
"itemid": 590532217,
"shortname": "ammo.nailgun.nails",
"displayName": {
"token": "ammo.nailgun.nails",
"english": "Nailgun Nails"
}
}
ItemModProjectile
{
"more": "stuff"
}`;
let obj = parseFirstJson(text);
console.log(JSON.stringify(obj, null, ' '));
输出:
{
"itemid": 590532217,
"shortname": "ammo.nailgun.nails",
"displayName": {
"token": "ammo.nailgun.nails",
"english": "Nailgun Nails"
}
}解释:
^ - string[^\{]*的开始-扫描直到第一次{(之前-捕获组[\s\S]*?的开始-谨慎扫描所有字符until:[\r\n]\} -一个}在line的开始。
) -捕获结束group[\s\S]*$ -扫描其他一切,直到行结束。
https://stackoverflow.com/questions/66245367
复制相似问题