Parsing JSON Without Quoted Keys

Parsing json, key without quotes

I originally put this in as a comment, but I think it counts as an answer albeit not necessarily a very helpful one.

The example you posted is not JSON. Check the JSON syntax. The only unquoted entities allowed except for numbers, objects and arrays are null, true, false. So the keys in your example are invalid and so are the non numeric values.

So you really should raise a defect report with the service provider (if they are claiming that they are producing JSON, rather than some modified version of it).

If they refuse to fix the problem, you'll need to write a nearly-JSON parser or find an existing one that is less strict about syntax.

Parsing JSON without quoted keys

If the data is pretty well formed other than that, a simple regex might do it:

irb(main):009:0> '{name:"hello", age:"23"}'.gsub(/([a-z]+):/, '"\1":')
=> "{\"name\":\"hello\", \"age\":\"23\"}"

Parse Json without quotes in Python

If the producer of the data is consistent, you can start with something like the following, that aims to bridge the JSON gap.

import re
import json

source = {
"Records": "{Output=[{_fields=[{Entity=ABC , No=12345, LineNo= 1, EffDate=20200630}, {Entity=ABC , No=567, LineNo= 1, EffDate=20200630}]}"
}

s = source["Records"]

# We'll start by removing any extraneous white spaces
s2 = re.sub('\s', '', s)

# Surrounding any word with "
s3 = re.sub('(\w+)', '"\g<1>"', s2)

# Replacing = with :
s4 = re.sub('=', ':', s3)

# Lastly, fixing missing closing ], }
## Note that }} is an escaped } for f-string.
s5 = f"{s4}]}}"

>>> json.loads(s5)
{'Output': [{'_fields': [{'Entity': 'ABC', 'No': '12345', 'LineNo': '1', 'EffDate': '20200630'}, {'Entity': 'ABC', 'No': '567', 'LineNo': '1', 'EffDate': '20200630'}]}]}

Follow up with some robust testing and have a nice polished ETL with your favorite tooling.

Parse the json string without quotes into json

The main question is really where did you get the string from, but anyways, here is a solution.

var obj = eval('(' + str + ')');
var json = JSON.stringify(obj);

Parse JSON with no quotes in JavaScript

Well the best answer is fix the buggy code in the service that does it.

So if you will not be able to use JSON.parse you can go old school and use eval or new Function.

var x = '{foo:"bar", "cat" : "dog"}';
eval("var o =" + x);
console.log(o);

or

var x = '{foo:"bar", "cat" : "dog"}';
var o = new Function("return " + x)();
console.log(o)

Use of these solutions opens you up to XSS attacks..

Another option is write a regular expression that tries to fix it

Not able to parse JSON without double quotes in Java using FasterXML Jackson

The form of your JSON string is invalid, it looks more like Properies class in Java.

Therefore, you can transform your invalid JSON string by replacing some characters to meet the format of .properties file, and then use Properties to read it as follows:

String inputStr = "{ht_missingConditions=null, employeeNumber=UMB1075962, firstName=Pete}";

inputStr = inputStr.replace("{", "").replace("}", "").replace(",", "\r\n");

Properties properties = new Properties();
properties.load(new ByteArrayInputStream(inputStr.getBytes(StandardCharsets.UTF_8)));
System.out.println(properties.toString()); // {ht_missingConditions=null, firstName=Pete, employeeNumber=UMB1075962}

Or you can also convert it to a Map and get similar result:

Map<String, String> propMap = properties.entrySet().stream()
.collect(Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue()),
(prev, next) -> next, HashMap::new
));
System.out.println(propMap.toString()); // {firstName=Pete, ht_missingConditions=null, employeeNumber=UMB1075962}


Related Topics



Leave a reply



Submit