Skip to content

Commit d950e6b

Browse files
authored
Merge pull request #795 from PayButton/feat/try-parsing-json
[#774] feat: try to parse it as JSON
2 parents ad6cff5 + b65e589 commit d950e6b

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

tests/unittests/validators.test.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,4 +350,47 @@ describe('parseOpReturn', () => {
350350
key: 'value=othervalue'
351351
})
352352
})
353+
it('Parses simple JSON', () => {
354+
const opReturnData = '{"foo": "bar"}'
355+
expect(v.parseOpReturnData(opReturnData)).toEqual({
356+
foo: 'bar'
357+
})
358+
})
359+
it('Parses nested JSON', () => {
360+
const opReturnData = '{"foo": {"bar": {"baz": {"qux": "qix"}}}}'
361+
const result = v.parseOpReturnData(opReturnData)
362+
expect(result).toEqual({
363+
foo: {
364+
bar: {
365+
baz: {
366+
qux: 'qix'
367+
}
368+
}
369+
}
370+
})
371+
})
372+
it('Parses number string into string', () => {
373+
// This large number, if interpreted as a number and not as a string,
374+
// will come out as 9007199254740996 due to floating point approximation
375+
const opReturnData = '9007199254740995'
376+
const result = v.parseOpReturnData(opReturnData)
377+
expect(result).toStrictEqual('9007199254740995')
378+
})
379+
it('Parses number string into string', () => {
380+
// JSON.parse would consider this as `0`
381+
const opReturnData = '-0'
382+
const result = v.parseOpReturnData(opReturnData)
383+
expect(result).toStrictEqual('-0')
384+
})
385+
it('Parses exponential number string into string', () => {
386+
// JSON.parse would consider this as `100000`
387+
const opReturnData = '10e5'
388+
const result = v.parseOpReturnData(opReturnData)
389+
expect(result).toStrictEqual('10e5')
390+
})
391+
it('Parses empty string into empty string', () => {
392+
const opReturnData = ''
393+
const result = v.parseOpReturnData(opReturnData)
394+
expect(result).toStrictEqual('')
395+
})
353396
})

utils/validators.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,16 @@ function splitAtFirst (str: string, separator: string): string[] {
366366
// key has the unparsable string as value.
367367
export function parseOpReturnData (opReturnData: string): any {
368368
const dataObject: any = {}
369+
// Try to parse it as JSON first, excluding simple numbers
370+
try {
371+
const jsonParsed = JSON.parse(opReturnData)
372+
if (typeof jsonParsed === 'number') {
373+
throw new Error()
374+
}
375+
return jsonParsed
376+
} catch {}
377+
378+
// Try to parse it as k=v pairs
369379
try {
370380
const keyValuePairs = opReturnData.split(' ')
371381
for (const kvString of keyValuePairs) {

0 commit comments

Comments
 (0)