-
-
Save samuraitruong/98b58a3bafd0345e6da6dc6950d52924 to your computer and use it in GitHub Desktop.
jsonp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Text.RegularExpressions; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
class Program | |
{ | |
static void Main() | |
{ | |
string jsonpFilePath = "path/to/your/jsonpfile.jsonp"; | |
string csvFilePath = "path/to/your/csvfile.csv"; | |
ConvertJsonpToCsv(jsonpFilePath, csvFilePath); | |
} | |
static void ConvertJsonpToCsv(string jsonpFilePath, string csvFilePath) | |
{ | |
// Read the JSONP file | |
string jsonpData = File.ReadAllText(jsonpFilePath); | |
// Remove the function call wrapper from the JSONP data | |
string jsonData = ExtractJsonFromJsonp(jsonpData); | |
// Parse the JSON data | |
JArray jsonArray = JArray.Parse(jsonData); | |
// Get column names from the first object in the array | |
var columns = new List<string>(); | |
foreach (JToken token in jsonArray[0]) | |
{ | |
columns.Add(token.Path); | |
} | |
// Write to CSV file | |
using (StreamWriter writer = new StreamWriter(csvFilePath)) | |
{ | |
// Write column headers | |
writer.WriteLine(string.Join(",", columns)); | |
// Write each row | |
foreach (JObject jsonObj in jsonArray) | |
{ | |
List<string> rowValues = new List<string>(); | |
foreach (var column in columns) | |
{ | |
rowValues.Add(jsonObj[column]?.ToString() ?? ""); | |
} | |
writer.WriteLine(string.Join(",", rowValues)); | |
} | |
} | |
Console.WriteLine($"JSONP file converted to CSV: {csvFilePath}"); | |
} | |
static string ExtractJsonFromJsonp(string jsonp) | |
{ | |
// Use regex to extract the JSON data from the JSONP string | |
Match match = Regex.Match(jsonp, @"^[^\(]*\((.*)\);$", RegexOptions.Singleline); | |
if (match.Success) | |
{ | |
return match.Groups[1].Value; | |
} | |
else | |
{ | |
throw new InvalidOperationException("Invalid JSONP format"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment