Array format to JSON format [closed]

Asked by Tiffany Vasquez on
10 Answers

Answer by Kelly Quinn

Arrays in JSON are almost the same as arrays in JavaScript.,For example, given below is a JSON document that contains a JSON array of access rights.,We can store an array inside another JSON array. It is known as an array of arrays or a multi-dimensional JSON array.,JSON array can store string, number, boolean, object or other array inside JSON array.

For example, given below is a JSON document that contains a JSON array of access rights.

{
	"name" : "Admin",
	"age" : 36,
	"rights" : [ "admin", "editor", "contributor" ]
}

You can access the array values by using the index number:

x = myObj.rights[0];

Program output.

admin

Use the delete keyword to delete items from an array:

delete myObj.rights[1];

Use the index number to modify an array:

myObj.rights[1] = "blogger";

We can access array values by using a for-in loop:

for (i in myObj.rights) 
{
	x = myObj.rights[i];
	console.log(x);
}

Program output.

admin
editor
contributor

We can store an array inside another JSON array. It is known as an array of arrays or a multi-dimensional JSON array.

var siteInfo = {
	"name" : "blogger",
	"users" : [
		[ "admins", "1", "2" , "3"],
		[ "editors", "4", "5" , "6"],
	]
}

A simple for loop to iterate over a multi-dimensional array in JSON.

for (i in siteInfo .users) 
{
	for (j in siteInfo.users[i]) 
	{
		x = siteInfo.users[i][j];
		console.log(x);
	}
}

Program Output:

admins
1
2
3
editors
4
5
6

Source: https://restfulapi.net/json-array/


Answer by Jude Walters

Generating and Parsing JSON Data, Generating and Parsing JSON Data ,When objects and arrays contain other objects or arrays, the data has a tree-like structure., When objects and arrays contain other objects or arrays, the data has a tree-like structure.

{
   "firstName": "Duke",
   "lastName": "Java",
   "age": 18,
   "streetAddress": "100 Internet Dr",
   "city": "JavaTown",
   "state": "JA",
   "postalCode": "12345",
   "phoneNumbers": [
      { "Mobile": "111-111-1111" },
      { "Home": "222-222-2222" }
   ]
}

Source: https://javaee.github.io/tutorial/jsonp001.html


Answer by Rex Leon

2 For the record, you are turning an Array into an Object. Using the word JSON, which is a text format, in this context is confusing. – Shilly Mar 15 '19 at 14:00 , Please use the correct tags so users that can answer your question can find it. The tags you had selected were not relevant to angular or angularjs. This question was about javascript and json, nothing more was needed. – Igor Mar 15 '19 at 14:02 , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

You can use Array#reduce method.

var res = arrayList
  // iterate over the array
  .reduce((obj, o) => {
    // define property 
    obj[o.name] = o.value;
    // return the object
    return obj;
    // set initial value as an empty object
  }, {})
var arrayList = [{
    name: "01",
    value: "3424234234"
  },
  {
    name: "17",
    value: "26021734"
  },
  {
    name: "10",
    value: "435345"
  },
  {
    name: "21",
    value: "3453"
  }
];

var res = arrayList.reduce((obj, o) => {
  obj[o.name] = o.value;
  return obj;
}, {})

console.log(res)

Same with ES6 object destructuring.

var res = arrayList.reduce((obj, { name, value }) => {
  obj[name] = value;
  return obj;
}, {})
var arrayList = [{
    name: "01",
    value: "3424234234"
  },
  {
    name: "17",
    value: "26021734"
  },
  {
    name: "10",
    value: "435345"
  },
  {
    name: "21",
    value: "3453"
  }
];

    

console.log(res)

One-liner solution with spread syntax :

var res = arrayList.reduce((obj, { name, value }) => ({ [name] : value, ...obj }), {})

Or

var res = arrayList.reduce((obj, { name, value }) => (obj[name] = value, obj ), {})

Source: https://stackoverflow.com/questions/55184187/how-to-format-array-list-to-json


Answer by Amina Stark

members contains an array populated by objects. We want to access the second object inside the array, so we use [1].,Inside this object, we want to access the powers property, so we use ["powers"].,Inside that we want to access the members property, so we use ["members"].,Inside the powers property is an array containing the selected hero's superpowers. We want the third one, so we use [2].

{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

Source: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON


Answer by Ryland Roberson

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ]. ,A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1. ,In contrast to regular arrays from the BDL, the elements of a JSON array can be of different data types. The following data types are allowed for JSON arrays:

Examples

[ ] //Empty JSON array

[ 0, 1, 2, 3, 4, 5]

[ “StringValue”, 10, 20.13, true, null ]

[
 {
   “Name” : “Nested Object”
 },
 [ 10, 20, true, 40, “Nested Array” ]
]

Source: https://www.microfocus.com/documentation/silk-performer/205/en/silkperformer-205-webhelp-en/GUID-0847DE13-2A2F-44F2-A6E7-214CD703BF84.html


Answer by Treasure Blair

Values can be an object, an array, Boolean, string, digits or NULL.,So here empRights is an array of strings enclosed inside square brackets with quotations.,This is a guide to JSON Array of Strings. Here we also discuss the introduction and how json array of string works? along with different examples and its code implementation. You may also have a look at the following articles to learn more –,We can also store multi dimensional array of strings,

[“value1”, “value2”, “value3”,……..]

[“value1”, “value2”, “value3”,……..]

Source: https://www.educba.com/json-array-of-strings/


Answer by Leighton Shields

Array: an ordered list of zero or more elements, each of which may be of any type. Arrays use square bracket notation with comma-separated elements.,JSON is a language-independent data format. It was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data. JSON filenames use the extension .json. ,XML separates "data" from "metadata" (via the use of elements and attributes), while JSON does not have such a concept. ,Several serialisation formats have been built on or from the JSON specification. Examples include GeoJSON, JSON-LD, Smile (data interchange format), UBJSON, JSON-RPC, JsonML, and JSON→URL.[58]

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null
}

Source: https://en.wikipedia.org/wiki/JSON


Answer by Memphis Lucas

Let's take a look at JSON objects and JSON arrays and compare them to their JavaScript counterparts.,JSON arrays work pretty much the same way as arrays in JavaScript, and can contain strings, booleans, numbers, and other JSON objects. For example:,As the name suggests, JSON.parse() takes a JSON string and parses it into a JavaScript object literal or array.,With that understanding, let's look at different ways to parse JSON in JavaScript.

{
  "name": "Jane Doe",
  "favorite-game": "Stardew Valley",
  "subscriber": false
}

Source: https://www.freecodecamp.org/news/json-stringify-example-how-to-parse-a-json-object-with-javascript/


Answer by Kade Sheppard

The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string.,The JSON file usually contains one key prop representing the tree of the object inside the file content. If you want to use the JSON data along with the key, then the parse() function can be used.,To convert the array from the local JSON file to the JavaScript-based object, you can use the ES6 import statement to import the local JSON file and use it in the existing components.,Here in the above import statement, the Students will represent the source of the JSON file, and you need to provide its path from where the JSON file exists into the project directory. Below is the sample Students.json file that you can use as demo.

1JSON.parse(JSON_source)

Source: https://www.pluralsight.com/guides/convert-a-json-file-to-an-array-in-react