0

Here is sample JSON data. It has one 'PO' and inside 'PO' there are multiple 'SO' nodes. Inside an 'SO' node there can be multiple nodes each containing one 'B', 'R', 'F'.

{
    "PO": [
        {
            "SO": [
                {
                    "B": "XXX",
                    "R": "YYY",
                    "F": "ZZZ"
                },
                {
                    "B": "MMM",
                    "R": "NNN",
                    "F": "PPP"
                }
            ],
            "SO": [
                {
                    "B": "111",
                    "R": "222",
                    "F": "333"
                },
                {
                    "B": "333",
                    "R": "444",
                    "F": "555"
                },
                {
                    "B": "666",
                    "R": "777",
                    "F": "888"
                }
            ]
        }
    ]
}

I want this data to be like this

{
    "PO": [
        {
            "B": "XXX",
            "R": "YYY",
            "F": "ZZZ"
        },
        {
            "B": "MMM",
            "R": "NNN",
            "F": "PPP"
        },
        {
            "B": "111",
            "R": "222",
            "F": "333"
        },
        {
            "B": "333",
            "R": "444",
            "F": "555"
        },
        {
            "B": "666",
            "R": "777",
            "F": "888"
        }
    ]
}

How can I do this in Javascript?

I tried obj.PO[0].SO where obj is the JSON object and some replace functions to replace the 'SO' nodes, but couldn't get it to work.

272727
  • 9
  • 1

1 Answers1

0

The problem is that your JSON contains duplicate keys. This means that when JSON.parse converts the JSON string into an object, one value will override the other, and as such you will obtain either

{
    "PO": [
        {
            "SO": [
                {
                    "B": "XXX",
                    "R": "YYY",
                    "F": "ZZZ"
                },
                {
                    "B": "MMM",
                    "R": "NNN",
                    "F": "PPP"
                }
            ]
        }
    ]
}

or

{
    "PO": [
        {
            "SO": [
                {
                    "B": "111",
                    "R": "222",
                    "F": "333"
                },
                {
                    "B": "333",
                    "R": "444",
                    "F": "555"
                },
                {
                    "B": "666",
                    "R": "777",
                    "F": "888"
                }
            ]
        }
    ]
}

the ideal solution would be to have your input be proper JSON without key collisions; as a workaround, you can instead use an event-based ("SAX style") JSON parser such as clarinet to preserve all information.

Luatic
  • 8,513
  • 2
  • 13
  • 34