HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Substitution of different occurrences of a string with changing patterns

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
substitutionoccurrenceswithpatternsdifferentchangingstring

Problem

I need to parse an invalid JSON string in which I find many repetitions of the same key, like the following snippet:

[...]
"term" : {"Entry" : "value1", [.. other data ..]},
"term" : {"Entry" : "value2", [.. other data ..]},
[...]


I thought of appending a suffix to each key, and I do it using the following code:

word = "term"
offending_string = '"term" : {"Entry"'
replacing_string_template = '"%s_d" : {"Entry"'

counter = 0
index = 0
while index != -1:
    # result is the string containing the JSON data
    index = result.find(offending_string, index)
    result = result.replace(offending_string,
                replacing_string_template % (word, counter), 1)
    counter += 1


It works, but I'd like to know if it is a good approach and if you would do this in a different way.

Solution

import json

def fixup(pairs):
   return pairs

decoded = json.loads(bad_json, object_pairs_hook = fixup)


object_pairs_hook is a more recent addition. If you have an older version of python you may not have it. The resulting python object will contain lists of pairs (including duplicates) rather then dictionaries.

Code Snippets

import json

def fixup(pairs):
   return pairs

decoded = json.loads(bad_json, object_pairs_hook = fixup)

Context

StackExchange Code Review Q#968, answer score: 4

Revisions (0)

No revisions yet.