-2

I have a large JSON file that looks similar to the code below. Is there anyway I can iterate through each object, look for the field "element_type" (it is not present in all objects in the file if that matters) and extract or write each object with the same element type to a file? For example each user would end up in a file called user.json and each book in a file called book.json?

I thought about using javascript but to my knowledge js can't write to files, I also tried to do it using linux command line tools by removing all new lines, then inserting a new line after each "}," and then iterating through each line to find the element type and write it to a file. This worked for most of the data; however, where there were objects like the "problem_type" below, it inserted a new line in the middle of the data due to the nested json in the "times" element. I've run out of ideas at this point.

{
    "data": [
        {
            "element_type": "user",
            "first": "John",
            "last": "Doe"
        },
        {
            "element_type": "user",
            "first": "Lucy",
            "last": "Ball"
        },
        {           
            "element_type": "book",
            "name": "someBook",
            "barcode": "111111"
        },
        {           
            "element_type": "book",
            "name": "bookTwo",
            "barcode": "111111"
        },
        {
            "element_type": "problem_type",
            "name": "problem object",
            "times": "[{\"start\": \"1230\", \"end\": \"1345\", \"day\": \"T\"}, {\"start\": \"1230\", \"end\": \"1345\", \"day\": \"R\"}]"
        }
    ]
}
Jimmy Reg
  • 3
  • 1

1 Answers1

0

I would recommend Java for this purpose. It sounds like you're running on Linux so it should be a good fit.

You'll have no problems writing to files. And you can use a library like this - http://json-lib.sourceforge.net/ - to gain access to things like JSONArray and JSONObject. Which you can easily use to iterate through the data in your JSON request, and check what's in "element_type" and write to a file accordingly.

b85411
  • 9,420
  • 15
  • 65
  • 119