-2
{
    "student": [
        {
            "name": "TEST",
            "id": "1234",
            "@class" : "10"
        }
    ],
    "student": [
        {
            "name": "TEST12",
            "id": "1235",
            "@class" : "12"
        }
    ]
}

How to generate the JSON like this from classObj or any other way?

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Dinesh
  • 21
  • 5
  • 2
    Instead of one array per "student" make it one array for all student records, `"student": [{"name":...}, {"name":...}]` – Joakim Danielson Sep 24 '21 at 10:25
  • Thanks @JoakimDanielson. I need structure like this instead of one array. Is it possible? – Dinesh Sep 24 '21 at 10:31
  • 1
    No, you don't need that. I of course have no idea what you are trying to do here but you need to re-think your solution or you have misunderstood some requirement because you can't have duplicate keys and there is really no point in having them either. – Joakim Danielson Sep 24 '21 at 10:37
  • If you must have a structure that looks like this then can you replace "student" at the outer level with something that is actually a map key such as the "id" element from the student details map? – Andy Brown Sep 24 '21 at 11:46

2 Answers2

1

The format you describe, with duplicated keys, is not a good one. As RFC 8259 says:

The names within an object SHOULD be unique.

As such, you're unlikely to find a library that makes it easy to generate this format, and you can't predict which student consumers would use.

It's reasonable to compose JSON as strings, if you're careful. The outer structure is simple. Generate it by concatenating hardcoded strings of JSON, then concatenate a generated String for each individual student object.

Joe
  • 29,416
  • 12
  • 68
  • 88
0

This is considered an invalid JSON as per RFC-8259.

Instead you can group your students in an array

{
    "students": [
        {
            "name": "TEST",
            "id": "1234",
            "@class" : "10"
        },
        {
            "name": "TEST12",
            "id": "1235",
            "@class" : "12"
        }
    ]
}

Nergon
  • 443
  • 2
  • 14