Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,156,412 members, 7,830,093 topics. Date: Thursday, 16 May 2024 at 04:02 PM

Programming Challenge: Convert String to Json with a Loop - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / Programming Challenge: Convert String to Json with a Loop (5429 Views)

Professional Html,bootstrap,php,java,json Web Deloper. Pay After Service! / Jamb Past Questions API In JSON / English Dictionary In Xml/json Format (2) (3) (4)

(1) (2) (3) (Reply) (Go Down)

Programming Challenge: Convert String to Json with a Loop by Nobody: 8:49pm On Apr 20, 2016
Modified:

You are to loop through this string below with headers and rows to create a valid Json string.

"Country\tState\tTown\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n";


Which should produce the Json result below:

[{
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
}, {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}]


You can validate your Json result here: http://jsonlint.com

Disclaimer: Please only attempt this challenge if you know your are a dangerous programmer.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:03pm On Apr 20, 2016
You didn't even specify the .json file or the url .
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:08pm On Apr 20, 2016
proxy20:
You didn't even specify the .json file or the url . Are we json file generators .

put the json file or url here
www.json2csharp.com it will generate the class
open visual studio click on console project . In the main.cs put the json class generated . After that click

Edit >>Paste Json . click build

Sorry you miss understood me, the string would need to be converted to Json first before being converted to an object without listing the object properties.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:13pm On Apr 20, 2016
Where is the data that you want to store or are you creating an empty string with no data only general variables like age , town . undefined strings.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:31pm On Apr 20, 2016
proxy20:
Where is the data that you want to store or are you creating an empty string with no data only general variables like age , town . undefined strings.

The string is in a tab format "\t" copied from a table with columns and rows into a html textbox and it will give you the string I posted above. You will need to loop through this string using the split method.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:46pm On Apr 20, 2016
ok
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 10:20pm On Apr 20, 2016
proxy20:
Alright . You don't need Json , convert the excel style sheet to sql .
https://www.youtube.com/watch?v=MTX6kfPmACM

This challenge will allow a string with "\t" to be converted to Json.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 11:08pm On Apr 20, 2016
360 degrees k leg
Re: Programming Challenge: Convert String to Json with a Loop by larisoft: 6:33pm On Apr 21, 2016
dhtml18:
This kind of challenge get K-leg.


lol
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 9:13am On Apr 22, 2016
@dhtml18 and proxy20

This challenge has now been modified.
Now it's just a simple loop through the string below:

"Country\tState\tTown\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n";


Which should produce the Json result below:

[{
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
}, {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}]

You can validate your Json result here: http://jsonlint.com
Re: Programming Challenge: Convert String to Json with a Loop by larisoft: 11:56am On Apr 22, 2016

public static String solution(String s){


//get table rows;
String[] rows = s.split("\r\n" ) ;

//header rows are at index 0
String header = rows[0];
//break header into columns
String[] header_rows = header.split("\t" ) ;


//append each subsequent word to its corresponding header
//note that we start at 1
StringBuilder builder = new StringBuilder() ;

//just making the json valid
builder.append("{" ) ;
int counter = 1;
for(int i = 1; i < rows.length; i++){

//get this particular row
String[] thisRow = rows[i].split("\t" ) ;

//we add a counter to produce valid json
builder.append("\""+(counter++)+"\": {" ) ;
for(int j = 0; j < header_rows.length; j++){

//where the job is done
builder.append( "\""+header_rows[j] + "\" : \"" + thisRow[j]+"\"" ) ;

//if this is not the last item in this row, add a comma
if(header_rows.length-1>j){
builder.append(", " ) ;
}
}

builder.append("}" ) ;

//if this is not the last json bracket in this string, add comma
if(rows.length-1>i){
builder.append("," ) ;
}


}

builder.append("}" ) ;

return builder.toString() ;

}


this will produce:

{
"1": {
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
},
"2": {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}
}
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 12:33pm On Apr 22, 2016
larisoft:

this will produce:

{
"1": {
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
},
"2": {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}
}


Well done mate. Though I was expecting it in the format below, but with your code I'm sure you can do that easily.
[{
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
}, {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}]
Re: Programming Challenge: Convert String to Json with a Loop by cyrielo(m): 1:07pm On Apr 22, 2016
Re: Programming Challenge: Convert String to Json with a Loop by cyrielo(m): 1:14pm On Apr 22, 2016
var parse_json = function(raw_string){
var
string_array = raw_string.split("\r\n\r\n"wink,
json_keys = string_array[0].split("\t"wink,
json_values_array = string_array[1].split("\r\n"wink,
formatted_string = '',
final_string = '[',
i,
j;
for( i = 0; i < json_values_array.length; i++ ){
var json_values_array_items = json_values_array[i].split("\t"wink;
for( j = 0; j < json_values_array_items.length; j++){
formatted_string +=
"{\""+json_keys[j]+":\""+json_values_array_items[j]+"\"}";
if( (j + 1 ) < (json_values_array_items.length ) ) {
formatted_string += ",";
}
}
final_string += formatted_string;
if( (i + 1) < json_values_array.length )
final_string += ",";

//console.log(final_string);
formatted_string = '';
}
final_string+= ']';
return final_string;
};
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 1:23pm On Apr 22, 2016
@ cyrielo, please post the result you got.
Re: Programming Challenge: Convert String to Json with a Loop by cyrielo(m): 1:33pm On Apr 22, 2016
Febup:
@ cyrielo, please post the result you got.
console.log( parse_json("Country\tState\tTown\r\n\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n"wink );

//[{"Country:"Nigeria"},{"State:"Lagos State"},{"Town:"Lagos"},{"Country:"USA"},{"State:"Texas"},{"Town:"Dallas"},{"Country:""}]
Re: Programming Challenge: Convert String to Json with a Loop by cyrielo(m): 1:46pm On Apr 22, 2016
Modified

var parse_json = function( raw_string ){
var
string_array = raw_string.split( "\r\n\r\n" ),
json_keys = string_array[0].split( "\t" ),
json_values_array = string_array[1].split( "\r\n" ),
formatted_string = '',
final_string = '[',
i,
j;
for( i = 0; i < json_values_array.length; i++ ){
var json_values_array_items = json_values_array[i].split( "\t" );
for( j = 0; j < json_values_array_items.length; j++){
formatted_string +=
"{\""+json_keys[j]+":\""+json_values_array_items[j]+"\"}";
if( (j + 1 ) < (json_values_array_items.length ) ) {
formatted_string += ",";
}
}
final_string += formatted_string;
if( (i + 1) < json_values_array.length )
final_string += "],[";

//console.log(final_string);
formatted_string = '';
}
final_string+= ']';
return final_string;
};
console.log( parse_json( " Country\tState\tTown\r\n\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n " ) );
//[{"Country:"Nigeria"},{"State:"Lagos State"},{"Town:"Lagos"}],[{"Country:"USA"},{"State:"Texas"},{"Town:"Dallas"}],[{"Country:""}]
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 2:22pm On Apr 22, 2016
cyrielo:

console.log( parse_json("Country\tState\tTown\r\n\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n"wink );

//[{"Country:"Nigeria"},{"State:"Lagos State"},{"Town:"Lagos"},{"Country:"USA"},{"State:"Texas"},{"Town:"Dallas"},{"Country:""}]

Try to validate your Json string at this link: http://jsonlint.com

it gives the error below:

Error:
[{ "Country:" Nigeria "},{" State
--------------^
Expecting 'EOF', '}', ':', ',', ']', got 'undefined'
Re: Programming Challenge: Convert String to Json with a Loop by larisoft: 3:40pm On Apr 22, 2016
Febup:


Well done mate. Though I was expecting it in the format below, but with your code I'm sure you can do that easily.
[{
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
}, {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}]


well I aim to please:
public static String solution(String s){


//get table rows;
String[] rows = s.split("\r\n " ) ;

//header rows are at index 0
String header = rows[0];
//break header into columns
String[] header_rows = header.split("\t " ) ;


//append each subsequent word to its corresponding header
//note that we start at 1
StringBuilder builder = new StringBuilder( ) ;

//just making the json valid
builder.append("[ " ) ;
int counter = 1;
for(int i = 1; i < rows.length; i++){

//get this particular row
String[] thisRow = rows[i].split("\t" ) ;

builder.append(" { " );
for(int j = 0; j < header_rows.length; j++){

//where the job is done
builder.append( "\""+header_rows[j] + "\" : \"" + thisRow[j]+"\"" ) ;

//if this is not the last item in this row, add a comma
if(header_rows.length-1>j){
builder.append(", " ) ;
}
}

builder.append("}" ) ;

//if this is not the last json bracket in this string, add comma
if(rows.length-1>i){
builder.append("," );
}


}

builder.append("]" );

return builder.toString();

}

that will produce :

[{
"Country": "Nigeria",
"State": "Lagos State",
"Town": "Lagos"
}, {
"Country": "USA",
"State": "Texas",
"Town": "Dallas"
}]
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 4:31pm On Apr 22, 2016
@larisoft you are the first winner. Hope other gurus will come out of hibernation to have ago too grin

Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 10:29pm On Apr 22, 2016
I dont even know what the thread is about, too advanced coding, trolls to next thread ------->
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 11:13pm On Apr 22, 2016
dhtml18:
I dont even know what the thread is about, too advanced coding, trolls to next thread ------->

Come back here mate. There is no where for you to hide. After Sql, XLM, now Json is the next big thing for data storage and for data exchange as it is light weight on like the others, this is why it is popular with WebAPI. So now is the time for you to get your hands dirty with Json.
Re: Programming Challenge: Convert String to Json with a Loop by FrankLampard: 11:49pm On Apr 22, 2016
^^^
So?
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 2:01pm On Apr 23, 2016
FrankLampard:
^^^

So?
So drop your code.
Re: Programming Challenge: Convert String to Json with a Loop by cyrielo(m): 4:40pm On Apr 23, 2016
Oh didn't check he json validation thing
**Modified Code
This one passes the validation at least
Note: I made some modification to your string format.
Notice the double carriage return to separate keys from actual values and i removed the new line at the of the string it causes a new row.

var parse_json = function( raw_string ){
var
string_array = raw_string.split( "\r\n\r\n" ),
json_keys = string_array[0].split( "\t" ),
json_values_array = string_array[1].split( "\r\n" ),
formatted_string = '',
final_string = '[',
i,
j;

for( i = 0; i < json_values_array.length; i++ ){
var json_values_array_items = json_values_array[i].split( "\t" );
formatted_string += "{";
for( j = 0; j < json_values_array_items.length; j++){
formatted_string += "\""+ json_keys[j]+ "\":\"" +
json_values_array_items[j] +"\"";
if( (j + 1 ) < (json_values_array_items.length ) ) {
formatted_string += ",";
}
}
formatted_string += "}";
final_string += formatted_string;
if( (i + 1) < json_values_array.length )
final_string += ",";
formatted_string = '';
}
final_string+= ']';
return final_string;
};
var parsed_string = parse_json( "Country\tState\tTown\r\n\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas" );
console.log( (parsed_string) );

//[{"Country":"Nigeria","State":"Lagos State","Town":"Lagos"},{"Country":"USA","State":"Texas","Town":"Dallas"}]
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 6:06pm On Apr 23, 2016
cyrielo:
Oh didn't check he json validation thing
**Modified Code
Note: I made some modification to your string format.
Notice the double carriage return to separate keys from actual values and i removed the new line at the of the string it causes a new row.

Nice try but you cannot modify the string, the string has to remain the same for this challenge.
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 6:33pm On Apr 23, 2016
Febup:


Nice try but you cannot modify the string, the string has to remain the same for this challenge.
I hope nobody will dry from trying this challenge!
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 7:40pm On Apr 23, 2016
dhtml18:

I hope nobody will dry from trying this challenge!

I hope it won't get to that, think I should put a disclaimer at the top grin
Re: Programming Challenge: Convert String to Json with a Loop by nnasino(m): 10:34pm On Apr 23, 2016

//scala script for json serialization


val inputString = "Country\tState\tTown\r\nNigeria\tLagos State\tLagos\r\nUSA\tTexas\tDallas\r\n"
val lineArray = inputString.split("\r\n"wink
val rows = lineArray.tail

val placeRegex = """(.+)\t(.+)\t(.+)""".r

//print the json
print("["wink
for(row <- rows){
row match {
case placeRegex(country, state, town) =>
printf("""{"Country":"%s",%n"State":"%s",%n"Town":"%s"%n} """,country,state,town)
case _ => println("Unknown"wink
}
if( row != rows.last) print(", "wink
};
println("]"wink


my output:

[{"Country":"Nigeria",
"State":"Lagos State",
"Town":"Lagos"
} , {"Country":"USA",
"State":"Texas",
"Town":"Dallas"
} ]
Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 10:56pm On Apr 23, 2016
@nnasino

You are the second winner, well done bro.

2 Likes

Re: Programming Challenge: Convert String to Json with a Loop by Nobody: 12:18am On Apr 24, 2016
dhtml18:

I hope nobody will dry from trying this challenge!
Typo, i meant actually die in real life by trying to complete this code. Me, just looking at it, am sweating already and getting high-blood pressure.
Lawd have mercy, see this nnasino codes as e long like Lagos - Ibadan expressway.

(1) (2) (3) (Reply)

Thread For Nairaland Algorithm Questions / Web Development Using Java / Puzzle of the day

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 52
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.