抱歉,如果我的英语不好,如果您听不懂,请写评论(我会编辑帖子)。我有获取JSON并按顺序(How I can parse json with arrays by custom order?)解析的脚本。它适用于一种JSON。我的问题是,我需要同时解析几个JSON(如脚本3 JSON中的JSON)才能获得md5的正确顺序。
我尝试连接JSON文件以获取一个JSON进行解析,但未连接。脚本:
var jsonForparse =[]
for (page=1;page<3;page++) {
url = "https://some.url/to/json"+page+".json";
xhr.open('GET', url, false);
xhr.send();
json=xhr.responseText ;
//Parse json string
json=JSON.parse(json);
//Connect jsons to jsonForparse
js =json.concat(js)
}
//Parse jsonForparse
md5= ids.map(id => jsonForparse.posts.find(post => post.id === id))
我应该如何解析json或连接json以解析它们以获得md5的正确顺序例:应该得到:
md5=[12,34,56,78,90,100]
订单:
ids=[2227726,2277,2218681,22881,6659,2236659]
[Json1:
{
"posts":[
{
"id":2236659,
"file":{
"size":1325351,
"md5":"100"
}
},
{
"id":2227726,
"file":{
"size":1182791,
"md5":"12"
}
},
{
"id":2218681,
"file":{
"size":1241188,
"md5":"56"
}
}
]
}
Json2:
{
"posts":[
{
"id":6659,
"file":{
"size":1325351,
"md5":"90"
}
},
{
"id":2277,
"file":{
"size":1182791,
"md5":"34"
}
},
{
"id":22881,
"file":{
"size":1241188,
"md5":"78"
}
}
]
}
const obj1 = JSON.parse(json1)
const obj2 = JSON.parse(json2)
... \\ this could be a loop if you have more
const obj = [...obj1.posts, ...obj2.posts].sort((a,b) => a.file.md5 - b.file.md5)
const ids = obj.map(e => e.id)
const md5s = obj.map(e => e.file.md5)
const p = [1, 2, 3].map(idx => fetch(`https://some.url/to/json${idx}.json`).then(res => res.json()));
Promise.all(p).then(results => {
let posts = results.reduce((acc, val) => acc = [...acc, ...val.posts], [])
let sorted = ids.map(id => posts.find(post => post.id === id))
// do smthg here
});