在javascript中更新JSON.parsed对象

时间:2016-04-20 20:01:46

标签: javascript json parsing

我正在尝试更新已解析的对象.data是从服务器收到的JSON对象。

var document_text = JSON.parse(data.projectData[0]['document_text']);
for(var j = 0; j < document_text.length;j++)
{
    var k = JSON.parse(document_text[j]);
    var document_data = JSON.parse(k).text;
    var page_number = JSON.parse(k).page_number;
}

现在我想更新包含text和page_number字段的document_text对象。请注意我必须解析对象两次。首先解析外部值然后获取内部值。如何更新document_text的字段(即text,page_number)。

这是原始数据

 ["\"{\\\"text\\\":\\\"Osddsdsdsdsds \\\\n\\\\n to  as \\\\\\\"sdfdsdsfsdfsdfsdf\\\\\\\") and CPGsddsdsdsdssdROsdsdsdsdP sdsdds,  a \\\\sd  sdds\\\\n\\\\n\\\\f\\\",\\\"page_number\\\":44}\"","\"{\\\"text\\\":\\\"Page  14 \\\\n\\\\nsdfsdfsdfdscopysdsdds\\\n\\\\n\\\\f\\\",\\\"page_number\\\":45}]

1 个答案:

答案 0 :(得分:1)

var document_text = JSON.parse(data.projectData[0]['document_text']);

/* At this point, document_text is already a JSON object. Iterating over it with 
a for loop doesn't make much sense. You can now just access its properties directly. */

document_text.text = "Some other text";
document_text.page_numer = 1;

/* Now we can return it to where it came from by stringify'ing it */

data.projectData[0]['document_text'] = JSON.stringify(document_text);