无法在javascript中连接多个json

问题描述 投票:0回答:1

[抱歉,如果我的英语不好,如果您听不懂,请写评论(我会编辑帖子)。我有一个脚本,它获取json并使用order(How I can parse json with arrays by custom order?)进行解析。它适用于1 json。我的问题是我需要同时解析几个json(例如在脚本3 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"
         }
      }
   ]
}
javascript json userscripts
1个回答
0
投票

您需要像现在所做的那样将每个JSON解析为对象,然后再加入它们,之后必须对它们进行排序:

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)
© www.soinside.com 2019 - 2024. All rights reserved.