Sunay Hashimov
Sunay Hashimov

Reputation: 161

Text to JSON formatting

I'm wondering, can I have text like this:

ps:mandatory' child of Input command functions
Properties

ps:Source:
    f47437

ps:Created:
    2010-09-03T11:38:02.629Z

ps:ChangedBy:
    F47437

ps:Changed:
    2011-09-07T07:51:10.864Z

In JSON format. The problem is there ..that the file includes tens of thousands of that text type and they're like tree family. And my point is to convert it to JSON saving the same tree logic. I just wanted to ask for my own knowledge.

Upvotes: 0

Views: 145

Answers (1)

mttdbrd
mttdbrd

Reputation: 1831

Do you mean like this?

{
    "ps:mandatory": "Properties",
    "ps:Source:": "f47437",
    "ps:Created:": "2010-09-03T11:38:02.629Z",
    "ps:ChangedBy:": "F47437",
    "ps:Changed:": "2011-09-07T07:51:10.864Z"
}

It's important to remember that JSON is unordered so you will most likely lose the order of the tags when storing it in JSON. If order is important, consider another file format.


The following code will turn your data above into JSON. Compiles and works:

import org.json.*;
public class CreateMyJSON
{
    public static void main(String[] args)
    {
        String testData = "ps:mandatory\nProperties\n\nps:Source:\n    f47437\n\nps:Created:\n    2010-09-03T11:38:02.629Z\n\nps:ChangedBy:\n    F47437\n\nps:Changed:\n    2011-09-07T07:51:10.864Z\n\n";
        CreateMyJSON cmj = new CreateMyJSON();
        System.out.println(cmj.getJSONFromString(testData));
        }

    public String getJSONFromString(String theData)
    {   
        JSONObject jso = new JSONObject();
        //no error checking, but replacing double returns
        //to make this simpler
        String massagedData = theData.replaceAll("\n\n", "\n");
        String[] splits = massagedData.split("\n");
        for(int i = 0; i < splits.length; i++)
        {
            jso.put(splits[i].trim(), splits[++i].trim());
        }

        return jso.toString();
    }
}

Upvotes: 2

Related Questions