Skip to content

Commit f552158

Browse files
committed
added json key creation logic
1 parent 156f1d3 commit f552158

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

src/interpreter.spec.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,12 @@ describe('Interpreter', () => {
124124
it('json obj', () => {
125125
expect(e.eval("x = {m1: 1+2*3, m2: 'ee'}\nx.m1")).toBe(7);
126126
expect(e.eval("x = {'m1': 1+2*3}\nx.m1")).toBe(7);
127-
expect(e.eval("x = {'m'+1: 1+2*3}\nx.m1")).toBe(7);
127+
expect(e.eval("x = {['m'+1]: 1+2*3}\nx.m1")).toBe(7);
128+
});
129+
130+
it('json with dynamic key', () => {
131+
expect(e.eval("p = 'prop'\nx = {[p + '_'+1]: 1+2*3}\nx.prop_1")).toBe(7);
132+
expect(e.eval("p = {x:'prop'}\nx = {[p.x + '_'+1]: 1+2*3}\nx.prop_1")).toBe(7);
128133
});
129134

130135
it('json single name prop', () => {

src/parser/parser.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -550,12 +550,21 @@ export class Parser {
550550
value: this.createExpressionNode(keyValue[0])
551551
} as ObjectPropertyInfo;
552552

553-
props.push(pInfo);
553+
props.push(pInfo);
554554
} else if (keyValue.length === 2) {
555-
// unquoted string becomes a variable, so, we don't need it, that is why we are creating const node explicitlely
556-
const name = (keyValue[0].length === 1 && !`'"`.includes((getTokenValue(keyValue[0][0]) as string)[0]))
557-
? new ConstNode(keyValue[0][0])
558-
: this.createExpressionNode(keyValue[0]);
555+
556+
let name: AstNode | null = null;
557+
const namePart = keyValue[0];
558+
559+
if (namePart.length === 1) {
560+
name = new ConstNode(namePart[0]);
561+
} else if (getTokenValue(namePart[0]) === '['
562+
&& getTokenValue(namePart[namePart.length - 1]) === ']') {
563+
name = this.createExpressionNode(namePart.slice(1, namePart.length - 1))
564+
} else {
565+
throw new Error(`Incorrect JSON. Can't resolve Key field. That should either constant or expression in []`)
566+
}
567+
559568
const pInfo = {
560569
name,
561570
value: this.createExpressionNode(keyValue[1])

0 commit comments

Comments
 (0)