How to escape JSON string for CSV parsing? - json

A bit of an odd question perhaps.
I'm trying to Store a JSON string appropriately in a CSV column as a string. It works OK when generating the CSV file, however parsing the CSV file with the JSON in it is a problem.
I've tried "{"prop": "Val"...}", "{""prop"": ""Val""...}", "{\"prop\": \"Val\"...}", "{\""prop\"": \""Val\""...}"
However none of them parse well at all.
Please help!

The correct answer here is to double quote the JSON string so this:
{ "a": 10 }
converts into this:
"{ ""a"": 10 }"

You can use the following replace logic to escape your JSON string:
`"${YOUR_JSON_STR.replace(/\"/g, '""')}"`

Related

How to escape single quotes in json string? JSON::ParserError Ruby

I'm getting
/json/common.rb:156:in `parse': 783: unexpected token at '' (JSON::ParserError) while trying to parse a json file in ruby. The problem was because there were some single quotes in one of the strings:
parsed = JSON.parse("{
\"key1\":\"value1\",
\"key2\":\"value2\",
\"key3\":12345,
\"key4\":\"''value4''\",
}")
Is there a way to escape the single quotes in the strings without affect words like don't? The json is read from a file using JSON.parse(file.get_input_stream.read) that's why there are \.
The single quotes aren't your problem, your problem is that you have a stray trailing comma:
parsed = JSON.parse("{
\"key1\":\"value1\",
\"key2\":\"value2\",
\"key3\":12345,
\"key4\":\"''value4''\",
}") #--------------------^ This should not be there.
JSON doesn't allow that comma so you don't actually have a JSON file.
You should figure out where the file came from and fix that tool to produce real JSON rather than the "looks mostly like JSON" that is currently being written to the file.

Double-quote inside Json inside CSV: do I need to escape the backslash?

I have a CSV file that contains a JSON string, which itself has a double-quote in one of its values. This means that the double quote must be escaped twice, first with another double-quote, and then with a backslash. However, I was not able to get this to work until I had escaped the backslash as well! Otherwise, I got a JSON parse error.
In other words, this raw value: " should became this in JSON: \" but then this did not work in the CSV file (JSON Parse Error): \"" but THIS did: \\""
Or, for a clearer example:
Value with double quote: You "know" it!
JSON: [{ "value" : "You \"know\" it!" }]
CSV (JSON Parse Error): "John Smith","[{ ""value"" : ""You \""know\"" it!"" }]"
CSV (DID work): "John Smith","[{ ""value"" : ""You \\""know\\"" it!"" }]"
This seems a bit unexpected. It's as if I have to escape a backslash in JSON. Why would I need to do this?
If it makes any difference, I'm using Java to parse all this, with OpenCSV for parsing the CSV data and Gson for parsing the JSON data.
Hmm, it's old question, but still, I needed to do something similar. My solution was to save csv in db, and then export it to json format.

How to load a JSON file in python 2.7

I am not able to load the following 'data.json' file in python 2.7.11,
file data.json
{
"name":xyz,
"age":12
}
The code i am using the load the above file,
import json
json_data = open ('data.json').read ()
json.loads(json_data)
I always get the following error
ValueError: No JSON object could be decoded
In the meantime,i also tried using yaml.load and it worked fine. But i wanted to know what is that i am doing wrong.
Your JSON is invalid.
Remember, if you're using alphabetical characters in a json Value, it's a string. So you have to write it within double quotes, like so:
{
"name":"xyz",
"age":12
}
Hopefully, this fix should solve your problem.

How do I get strings from a JSON file?

I'm writing a internationalized desktop program written in Vala where a use an extern JSON file to store a list of languages.
I'm using gettext for l10n so if I get the string from the json file and I do something like _(string_var) I could get the translated string. The problem is that I don't know how can I add the string to the pot file using xgettext or some similar tool.
Any idea??
If the tool jq (http://stedolan.github.io/jq/) is an option for you, below might work;
$ curl -s https://raw.githubusercontent.com/chavaone/gnomecat/master/data/languages.json | jq .languages[43].name
"English"
The solution I finally use was to modify the JSON file to use double quoted strings only when I wanted to translate that string. For example:
{
'code' : 'es',
'name' : "Spanish; Castilian",
'pluralform' : 'nplurals=2; plural=(n != 1);',
'default-team-email': 'gnome-es-list#gnome.org'
}
In the previous piece of JSON file the only string I wanted to translate was "Spanish; Castillian". Then in the POTFILES.in, I just use the gettext/quoted type.
# List of source files containing translatable strings.
# Please keep this file sorted alphabetically.
[encoding: UTF-8]
[type: gettext/quoted]data/languages.json
[type: gettext/quoted]data/plurals.json
[type: gettext/glade]data/ui/appmenu.ui
[...]

Unescaping Characters in a JSON response string

I made a JSON request that gives me a string that uses Unicode character codes that looks like:
s = "\u003Cp\u003E"
And I want to convert it to:
s = "<p>"
What's the best way to do this in Python?
Note, this is the same question as this one, only in Python except Ruby. I am also using the Posterous API.
>>> "\\u003Cp\\u003E".decode('unicode-escape')
u'<p>'
If the data came from JSON, the json module should already have decoded these escapes for you:
>>> import json
>>> json.loads('"\u003Cp\u003E"')
u'<p>'
EDIT: The original question "Unescaping Characters in a String with Python" did not clarify if the string was to be written or to be read (later on, the "JSON response" words were added, to clarify the intention was to read).
So I answered the opposite question: how to write JSON serialized data dumping them to a unescaped string (rather than loading data from the string).
My use case was producing a JSON file from my own data dictionary, but the file contained scaped non-ASCII characters. So I did it like this:
with open(filename,'w') as jsonfile:
jsonstr = json.dumps(myDictionary, ensure_ascii=False)
print(jsonstr) # to screen
jsonfile.write(jsonstr) # to file
If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.
Taken from here: https://docs.python.org/3/library/json.html