D
D
danylokiz2018-06-21 11:14:03
iOS
danylokiz, 2018-06-21 11:14:03

How to parse json array into 2 different arrays?

I have a json array and I need to parse it into 2 different arrays. Here's what it looks like:

"United Arab Emirates" : "AED",
        "Afghanistan" : "AFN",
        "Albania" : "ALL",
        "Armenia" : "AMD",
        "Netherlands Antilles" : "ANG",
        "Angola" : "AOA",
        "Argentina" : "ARS",
        "Australia" : "AUD",

Can I somehow parse it so that I only have this value "United Arab Emirates"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
danylokiz, 2018-07-04
@danylokiz

2 arrays are also created and done through append().

S
Sergey Sokolov, 2018-06-21
@sergiks

When parsing the given JSON, you will get not an array, but an object. Couples ключ: значение.
If only keys are needed, there is the Object.keys() method , which will return an array of keys:

var s = '{"United Arab Emirates":"AED","Afghanistan":"AFN","Albania":"ALL","Armenia":"AMD","Netherlands Antilles":"ANG","Angola":"AOA","Argentina":"ARS","Australia":"AUD"}';
var data = JSON.parse(s);
var countries = Object.keys(data); 

// United Arab Emirates,Afghanistan,Albania,Armenia,Netherlands Antilles,Angola,Argentina,Australia

A parsing operation is considered “heavy”, so even if you want to end up with not one but two objects, it’s better to parse it once, and then extract the necessary data from the resulting object.
But there is an option to process the data directly when parsing , passing the function as the second parameter.
var data = JSON.parse(s, function(k,v){
  return typeof v === "object" ? Object.keys(v) : v;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question