Проблема с массивом recipe
состоит в том, что каждый объект, который он содержит, имеет такую структуру:
{
"Poudre glaciale": {
"id": "13154",
"lvl": "190",
"quantity": "7"
}
}
Другими словами, каждый объект имеет один ключ (каждый раз с другим именем), и объект, который вы хотите достичь, вложен в этот переменный ключ, что затрудняет достижение.
Вы можете получить доступ к названию ключа («poudre glaciale»), используя Object.keys(obj)[0]
. Затем вы можете легко добраться до подобъекта:
const recipe = [{
"Galet brasillant": {
"id": "12740",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/12740-galet-brasillant",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/15289.w48h48.png",
"type": "Galet",
"lvl": "150",
"quantity": "3"
}
},
{
"Poudre glaciale": {
"id": "13154",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13154-poudre-glaciale",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/48292.w48h48.png",
"type": "Poudre",
"lvl": "190",
"quantity": "7"
}
},
{
"Poil d'aisselle de Missiz Frizz": {
"id": "13935",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13935-poil-aisselle-missiz-frizz",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/54691.w48h48.png",
"type": "Poil",
"lvl": "200",
"quantity": "9"
}
},
{
"Pédoncule de Mérulor": {
"id": "13978",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13978-pedoncule-merulor",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/119008.w48h48.png",
"type": "Champignon",
"lvl": "200",
"quantity": "6"
}
},
{
"Œil de Cycloïde": {
"id": "13988",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13988-oeil-cycloide",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/109603.w48h48.png",
"type": "Œil",
"lvl": "200",
"quantity": "30"
}
},
{
"Queue de Sinistrofu": {
"id": "13991",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13991-queue-sinistrofu",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/65764.w48h48.png",
"type": "Queue",
"lvl": "200",
"quantity": "3"
}
},
{
"Bandelette du Comte Harebourg": {
"id": "13995",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/13995-bandelette-comte-harebourg",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/15831.w48h48.png",
"type": "Ressources diverses",
"lvl": "200",
"quantity": "1"
}
},
{
"Œil de verre": {
"id": "14145",
"url": "https://www.dofus-touch.com/fr/mmorpg/encyclopedie/ressources/14145-oeil-verre",
"imgUrl": "https://s.ankama.com/www/static.ankama.com/dofus/www/game/items/52/109604.w48h48.png",
"type": "Œil",
"lvl": "200",
"quantity": "1"
}
}
]
const output = recipe.map( obj => {
let keyName = Object.keys(obj)[0]; // "Galet brasillant", "poudre glaciale", etc.
return obj[keyName]; // the object containing attributes
})
console.log(output[0])
Редактировать:
[1118 ] Если вам нужен идентификатор «Poudre glaciale», вы должны сделать это:
Сначала отфильтруйте массив recipe
, чтобы оставить только нужный вам объект: recipe.filter( obj => Object.keys(obj)[0] === "Poudre glaciale")
Затем , извлеките первый (и единственный) объект из этого отфильтрованного массива с помощью [0]
Затем введите внутри клавиши "Poudre glaciale"
с помощью ["Poudre glaciale"]
И затем вы можете получить доступ к id
Итак, полное решение:
const id = recipe.filter( obj => Object.keys(obj)[0] === "Poudre glaciale")[0]["Poudre glaciale"].id
Json.NET - отличная библиотека .NET json. Поддерживает LINQ, чтение / запись и преобразование объектов в и из json.
Вот метод расширения для сериализации любого экземпляра объекта в JSON:
public static class GenericExtensions
{
public static string ToJsonString<T>(this T input)
{
string json;
DataContractJsonSerializer ser = new DataContractJsonSerializer(input.GetType());
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, input);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
}
Вам потребуется добавить ссылку на System.ServiceModel.Web, чтобы использовать DataContractSerializer.
If you're just looking for JSON encoding/decoding, there is an official System.Web extension library from Microsoft that does it, odds are you probably already have this assembly (System.Web.Extensions):
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Example:
using System;
using System.Web.Script.Serialization;
class App
{
static void Main(string[] args = null)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
String sJson = "{\"Name\": \"Your name\"}";
DesJson json = jss.Deserialize<DesJson>(sJson);
Console.WriteLine(json.Name);
}
}
class DesJson {
public string Name {get; set;}
}