JS возражают против строки JSON? [дубликат]

Проблема в том, что @api.onchange() работает на уровне просмотра, например,

=> Edit a record in form view
=> You change value on a `@api.onchange()` field, `sq_cost` in this case
=> `@api.onchange` function is fired, some other field value is changed `standard_price` in this case
**But nothing is changed on the database yet, cause you are still on edit mode**
=> Changes are stored in database only if you press save button.

Но в случае импорта из CSV ничего не меняется на уровне просмотра, значения изменяются непосредственно в базе данных, поэтому ни одно из этот процесс выполняется.

Решение:

вместо использования функции onchange на уровне просмотра, вы можете использовать compute function в поле standard_price с @api.depends('sq_cost'). Это работает на уровне базы данных, поэтому значения будут рассчитываться всякий раз, когда вы импортируете значение sq_cost. Что нужно иметь в виду:

** compute field is by default not stored, set `store=True`
** compute field is by default readonly, set `inverse='inverse_function'` to make this field editable
11
задан outis 26 December 2011 в 09:42
поделиться

3 ответа

В библиотеке Крокфорда есть два примера методов (которые были созданы @Anonymous):

JSON-строка для объекта:

var obj = JSON.parse('{ "property":"value" }');
alert (obj.property);

// value

Объект в JSON-строку:

var str = JSON.stringify({ "property":"value" })
alert (str);

//{ "property":"value" }

Также есть встроенные методы, чтобы сделать это в большинстве основных структур.

14
ответ дан 3 December 2019 в 07:39
поделиться

Стоит отметить, что ссылка Anonymous ( http://www.json.org/js.html ) укажет вам правильное направление поскольку страница также содержит информацию о том, как структурировать структуру данных JavaScript в текст JSON:

Стрингер JSON идет в обратном направлении, преобразуя структуры данных JavaScript в текст JSON.

В частности, найдите ссылку внизу страницы, которая указывает на JSON-анализатор с открытым исходным кодом и JSON stringifier.

0
ответ дан 3 December 2019 в 07:39
поделиться

Куот Крокфорд ( http://www.json.org/js.html ):

Чтобы преобразовать текст JSON в объект, вы можете использовать функцию eval (). eval () вызывает JavaScript компилятор. Поскольку JSON является правильным подмножество JavaScript, компилятор will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.

var myObject = eval('(' + myJSONtext + ')');

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. ...

To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

var myObject = JSON.parse(myJSONtext, reviver);

And then he develops the JSON prototype in the rest of the article.

The versions of Gecko used in Firefox 3 and 3.5 support JSON natively (https://developer.mozilla.org/En/JSON), which may be useful if your project is limited to a recent Gecko-based application.


As pointed out below, the interesting part about the text generator (not parser) is at https://github.com/douglascrockford/JSON-js/blob/master/json2.js and introduced with

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

var myJSONText = JSON.stringify(myObject, replacer);

Cyclic data structures and objects that aren't usefully serialized are obviously the only big caveats there.

2
ответ дан 3 December 2019 в 07:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: