Search code examples
javascriptjsonuserscripts

Fetch and join JSON objects from multiple API calls


Sorry if my English is bad and write comment if you don't understand (I will edit post). I have script that gets JSON and parses it with order (How I can parse json with arrays by custom order?). It works well for one JSON. My problem is that I need to parse several JSON (like in script 3 JSON) at the same time to get correct order of md5's.

I tried connect JSON files to get one JSON for parsing, but it is not connecting. Script:

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))

How should I parse json's or connect json's to parse them to get correct order of md5's Example: Should get:

md5=[12,34,56,78,90,100]

Order:

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"
         }
      }
   ]
}

Solution

  • You need to parse each JSON into object as you are doing for one now and than to join them, after which you have to sort them:

    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)